3 | | Here is an example https://dpaste.de/UORC |
| 3 | Here is an example. |
| 4 | {{{ |
| 5 | # create works, update_or_create does not. Should neither work? |
| 6 | class Choice(models.Model): |
| 7 | poll = models.ForeignKey(Poll) |
| 8 | choice_text = models.CharField(max_length=200) |
| 9 | votes = models.IntegerField(default=0) |
| 10 | |
| 11 | _credit = models.DecimalField('Credit', decimal_places = 5, max_digits=11, null=True) |
| 12 | |
| 13 | @property |
| 14 | def credit(self): |
| 15 | return 0 if self._credit is None else self._credit |
| 16 | |
| 17 | @credit.setter |
| 18 | def credit(self, value): |
| 19 | self._credit = value |
| 20 | |
| 21 | |
| 22 | In [7]: mk = Choice.objects.create(credit=123.3, poll_id=1) |
| 23 | |
| 24 | In [8]: mk |
| 25 | Out[8]: <Choice: > |
| 26 | |
| 27 | In [9]: mk.__dict__ |
| 28 | Out[9]: |
| 29 | {'_credit': 123.3, |
| 30 | '_state': <django.db.models.base.ModelState at 0x1116e3650>, |
| 31 | 'choice_text': u'', |
| 32 | 'id': 2, |
| 33 | 'poll_id': 1, |
| 34 | 'votes': 0} |
| 35 | |
| 36 | In [10]: ok = Choice.objects.update_or_create(defaults={'credit':123.3}, poll_id=1) |
| 37 | --------------------------------------------------------------------------- |
| 38 | FieldError Traceback (most recent call last) |
| 39 | <ipython-input-10-147ffa08785c> in <module>() |
| 40 | ----> 1 ok = Choice.objects.update_or_create(defaults={'credit':123.3}, poll_id=1) |
| 41 | |
| 42 | /usr/local/lib/python2.7/site-packages/django/db/models/manager.pyc in manager_method(self, *args, **kwargs) |
| 43 | 83 def create_method(name, method): |
| 44 | 84 def manager_method(self, *args, **kwargs): |
| 45 | ---> 85 return getattr(self.get_queryset(), name)(*args, **kwargs) |
| 46 | 86 manager_method.__name__ = method.__name__ |
| 47 | 87 manager_method.__doc__ = method.__doc__ |
| 48 | |
| 49 | /usr/local/lib/python2.7/site-packages/django/db/models/query.pyc in update_or_create(self, defaults, **kwargs) |
| 50 | 474 """ |
| 51 | 475 defaults = defaults or {} |
| 52 | --> 476 lookup, params = self._extract_model_params(defaults, **kwargs) |
| 53 | 477 self._for_write = True |
| 54 | 478 with transaction.atomic(using=self.db): |
| 55 | |
| 56 | /usr/local/lib/python2.7/site-packages/django/db/models/query.pyc in _extract_model_params(self, defaults, **kwargs) |
| 57 | 530 "Invalid field name(s) for model %s: '%s'." % ( |
| 58 | 531 self.model._meta.object_name, |
| 59 | --> 532 "', '".join(sorted(invalid_params)), |
| 60 | 533 )) |
| 61 | 534 return lookup, params |
| 62 | |
| 63 | FieldError: Invalid field name(s) for model Choice: 'credit'. |
| 64 | }}} |