summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorTim Graham <timograham@gmail.com>2016-10-13 11:02:02 -0400
committerTim Graham <timograham@gmail.com>2016-10-13 11:03:34 -0400
commit9c956ff2f559e7074b5e49449a16857e9c47e3bd (patch)
treeea5c3740e80b492b108d64d0fd0d4db469ca7d1b /docs
parentf0dd9dd72cdaa848dfddd83e5f9539d2ba712470 (diff)
[1.9.x] Fixed #27342 -- Corrected QuerySet.update_or_create() example.
Backport of 51b83d9e5113ea5b81d04f4d117bd5acd3c1b822 from master
Diffstat (limited to 'docs')
-rw-r--r--docs/ref/models/querysets.txt12
1 files changed, 8 insertions, 4 deletions
diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt
index 9d9c312466..5834e3d3e2 100644
--- a/docs/ref/models/querysets.txt
+++ b/docs/ref/models/querysets.txt
@@ -1793,21 +1793,25 @@ the given ``kwargs``. If a match is found, it updates the fields passed in the
This is meant as a shortcut to boilerplatish code. For example::
+ defaults = {'first_name': 'Bob'}
try:
obj = Person.objects.get(first_name='John', last_name='Lennon')
- for key, value in updated_values.iteritems():
+ for key, value in defaults.items():
setattr(obj, key, value)
obj.save()
except Person.DoesNotExist:
- updated_values.update({'first_name': 'John', 'last_name': 'Lennon'})
- obj = Person(**updated_values)
+ new_values = {'first_name': 'John', 'last_name': 'Lennon'}
+ new_values.update(defaults)
+ obj = Person(**new_values)
obj.save()
This pattern gets quite unwieldy as the number of fields in a model goes up.
The above example can be rewritten using ``update_or_create()`` like so::
obj, created = Person.objects.update_or_create(
- first_name='John', last_name='Lennon', defaults=updated_values)
+ first_name='John', last_name='Lennon',
+ defaults={'first_name': 'Bob'},
+ )
For detailed description how names passed in ``kwargs`` are resolved see
:meth:`get_or_create`.