summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorQuentin Agren <quentin.agren@sciencespo.fr>2018-03-25 08:04:36 +0200
committerTim Graham <timograham@gmail.com>2018-03-28 10:46:34 -0400
commit34c522283710c3866833134ddf1a397da03999e8 (patch)
tree69af61e21f00bade6669732998110cc458c4e9d7 /docs
parent1bf4646f9133f26547a0dccf2f8a4526d85f2ab3 (diff)
Fixed #29148 -- Doc'd how to use get_or_create() with Q objects.
Diffstat (limited to 'docs')
-rw-r--r--docs/ref/models/querysets.txt16
1 files changed, 14 insertions, 2 deletions
diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt
index b9a1eb5e83..d4a96af6c0 100644
--- a/docs/ref/models/querysets.txt
+++ b/docs/ref/models/querysets.txt
@@ -1857,8 +1857,20 @@ The above example can be rewritten using ``get_or_create()`` like so::
Any keyword arguments passed to ``get_or_create()`` — *except* an optional one
called ``defaults`` — will be used in a :meth:`get()` call. If an object is
-found, ``get_or_create()`` returns a tuple of that object and ``False``. If
-multiple objects are found, ``get_or_create`` raises
+found, ``get_or_create()`` returns a tuple of that object and ``False``.
+
+You can specify more complex conditions for the retrieved object by chaining
+``get_or_create()`` with ``filter()`` and using :class:`Q objects
+<django.db.models.Q>`. For example, to retrieve Robert or Bob Marley if either
+exists, and create the latter otherwise::
+
+ from django.db.models import Q
+
+ obj, created = Person.objects.filter(
+ Q(first_name='Bob') | Q(first_name='Robert'),
+ ).get_or_create(last_name='Marley', defaults={'first_name': 'Bob'})
+
+If multiple objects are found, ``get_or_create()`` raises
:exc:`~django.core.exceptions.MultipleObjectsReturned`. If an object is *not*
found, ``get_or_create()`` will instantiate and save a new object, returning a
tuple of the new object and ``True``. The new object will be created roughly