Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#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 Tim Graham, 8 years ago

Owner: changed from nobody to Tim Graham
Status: newassigned
Summary: update_or_create example is misleadingQuerySet.update_or_create() "shortcut to boilerplatish code" example is incorrect
Triage Stage: UnreviewedAccepted

comment:2 by Tim Graham, 8 years ago

Has patch: set

comment:3 by GitHub <noreply@…>, 8 years ago

Resolution: fixed
Status: assignedclosed

In 51b83d9e:

Fixed #27342 -- Corrected QuerySet.update_or_create() example.

comment:4 by Tim Graham <timograham@…>, 8 years ago

In aba8f2b5:

[1.8.x] Fixed #27342 -- Corrected QuerySet.update_or_create() example.

Backport of 51b83d9e5113ea5b81d04f4d117bd5acd3c1b822 from master

comment:5 by Tim Graham <timograham@…>, 8 years ago

In 9c956ff2:

[1.9.x] Fixed #27342 -- Corrected QuerySet.update_or_create() example.

Backport of 51b83d9e5113ea5b81d04f4d117bd5acd3c1b822 from master

comment:6 by Tim Graham <timograham@…>, 8 years ago

In e781197:

[1.10.x] Fixed #27342 -- Corrected QuerySet.update_or_create() example.

Backport of 51b83d9e5113ea5b81d04f4d117bd5acd3c1b822 from master

Note: See TracTickets for help on using tickets.
Back to Top