#27342 closed Bug (fixed)
QuerySet.update_or_create() "shortcut to boilerplatish code" example is incorrect
Reported by: | kakarukeys | Owned by: | Tim Graham |
---|---|---|---|
Component: | Documentation | Version: | 1.10 |
Severity: | Normal | Keywords: | update_or_create |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
In the documentation about update_or_create, the following code
try: obj = Person.objects.get(first_name='John', last_name='Lennon') for key, value in updated_values.iteritems(): setattr(obj, key, value) obj.save() except Person.DoesNotExist: updated_values.update({'first_name': 'John', 'last_name': 'Lennon'}) obj = Person(**updated_values) obj.save()
is said to be practically the same as:
obj, created = Person.objects.update_or_create( first_name='John', last_name='Lennon', defaults=updated_values)
however, in the former, updated_values is overwritten by John Lennon dictionary.
whereas, in the latter, John Lennon dictionary is overwritten by update_values.
suggested code change:
except Person.DoesNotExist: new_values = {'first_name': 'John', 'last_name': 'Lennon'} new_values.update(updated_values) obj = Person(**new_values) obj.save()
Change History (6)
comment:1 by , 8 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
Summary: | update_or_create example is misleading → QuerySet.update_or_create() "shortcut to boilerplatish code" example is incorrect |
Triage Stage: | Unreviewed → Accepted |
comment:2 by , 8 years ago
Has patch: | set |
---|
Note:
See TracTickets
for help on using tickets.
PR