Skip to content

Commit 9c956ff

Browse files
committed
[1.9.x] Fixed #27342 -- Corrected QuerySet.update_or_create() example.
Backport of 51b83d9 from master
1 parent f0dd9dd commit 9c956ff

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

docs/ref/models/querysets.txt

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1793,21 +1793,25 @@ the given ``kwargs``. If a match is found, it updates the fields passed in the
17931793

17941794
This is meant as a shortcut to boilerplatish code. For example::
17951795

1796+
defaults = {'first_name': 'Bob'}
17961797
try:
17971798
obj = Person.objects.get(first_name='John', last_name='Lennon')
1798-
for key, value in updated_values.iteritems():
1799+
for key, value in defaults.items():
17991800
setattr(obj, key, value)
18001801
obj.save()
18011802
except Person.DoesNotExist:
1802-
updated_values.update({'first_name': 'John', 'last_name': 'Lennon'})
1803-
obj = Person(**updated_values)
1803+
new_values = {'first_name': 'John', 'last_name': 'Lennon'}
1804+
new_values.update(defaults)
1805+
obj = Person(**new_values)
18041806
obj.save()
18051807

18061808
This pattern gets quite unwieldy as the number of fields in a model goes up.
18071809
The above example can be rewritten using ``update_or_create()`` like so::
18081810

18091811
obj, created = Person.objects.update_or_create(
1810-
first_name='John', last_name='Lennon', defaults=updated_values)
1812+
first_name='John', last_name='Lennon',
1813+
defaults={'first_name': 'Bob'},
1814+
)
18111815

18121816
For detailed description how names passed in ``kwargs`` are resolved see
18131817
:meth:`get_or_create`.

0 commit comments

Comments
 (0)