1. ==============
    
  2. Making queries
    
  3. ==============
    
  4. 
    
  5. .. currentmodule:: django.db.models
    
  6. 
    
  7. Once you've created your :doc:`data models </topics/db/models>`, Django
    
  8. automatically gives you a database-abstraction API that lets you create,
    
  9. retrieve, update and delete objects. This document explains how to use this
    
  10. API. Refer to the :doc:`data model reference </ref/models/index>` for full
    
  11. details of all the various model lookup options.
    
  12. 
    
  13. Throughout this guide (and in the reference), we'll refer to the following
    
  14. models, which comprise a blog application:
    
  15. 
    
  16. .. _queryset-model-example:
    
  17. 
    
  18. .. code-block:: python
    
  19. 
    
  20.     from datetime import date
    
  21. 
    
  22.     from django.db import models
    
  23. 
    
  24.     class Blog(models.Model):
    
  25.         name = models.CharField(max_length=100)
    
  26.         tagline = models.TextField()
    
  27. 
    
  28.         def __str__(self):
    
  29.             return self.name
    
  30. 
    
  31.     class Author(models.Model):
    
  32.         name = models.CharField(max_length=200)
    
  33.         email = models.EmailField()
    
  34. 
    
  35.         def __str__(self):
    
  36.             return self.name
    
  37. 
    
  38.     class Entry(models.Model):
    
  39.         blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    
  40.         headline = models.CharField(max_length=255)
    
  41.         body_text = models.TextField()
    
  42.         pub_date = models.DateField()
    
  43.         mod_date = models.DateField(default=date.today)
    
  44.         authors = models.ManyToManyField(Author)
    
  45.         number_of_comments = models.IntegerField(default=0)
    
  46.         number_of_pingbacks = models.IntegerField(default=0)
    
  47.         rating = models.IntegerField(default=5)
    
  48. 
    
  49.         def __str__(self):
    
  50.             return self.headline
    
  51. 
    
  52. Creating objects
    
  53. ================
    
  54. 
    
  55. To represent database-table data in Python objects, Django uses an intuitive
    
  56. system: A model class represents a database table, and an instance of that
    
  57. class represents a particular record in the database table.
    
  58. 
    
  59. To create an object, instantiate it using keyword arguments to the model class,
    
  60. then call :meth:`~django.db.models.Model.save` to save it to the database.
    
  61. 
    
  62. Assuming models live in a file ``mysite/blog/models.py``, here's an example::
    
  63. 
    
  64.     >>> from blog.models import Blog
    
  65.     >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
    
  66.     >>> b.save()
    
  67. 
    
  68. This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
    
  69. the database until you explicitly call :meth:`~django.db.models.Model.save`.
    
  70. 
    
  71. The :meth:`~django.db.models.Model.save` method has no return value.
    
  72. 
    
  73. .. seealso::
    
  74. 
    
  75.     :meth:`~django.db.models.Model.save` takes a number of advanced options not
    
  76.     described here. See the documentation for
    
  77.     :meth:`~django.db.models.Model.save` for complete details.
    
  78. 
    
  79.     To create and save an object in a single step, use the
    
  80.     :meth:`~django.db.models.query.QuerySet.create()` method.
    
  81. 
    
  82. Saving changes to objects
    
  83. =========================
    
  84. 
    
  85. To save changes to an object that's already in the database, use
    
  86. :meth:`~django.db.models.Model.save`.
    
  87. 
    
  88. Given a ``Blog`` instance ``b5`` that has already been saved to the database,
    
  89. this example changes its name and updates its record in the database::
    
  90. 
    
  91.     >>> b5.name = 'New name'
    
  92.     >>> b5.save()
    
  93. 
    
  94. This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
    
  95. the database until you explicitly call :meth:`~django.db.models.Model.save`.
    
  96. 
    
  97. Saving ``ForeignKey`` and ``ManyToManyField`` fields
    
  98. ----------------------------------------------------
    
  99. 
    
  100. Updating a :class:`~django.db.models.ForeignKey` field works exactly the same
    
  101. way as saving a normal field -- assign an object of the right type to the field
    
  102. in question. This example updates the ``blog`` attribute of an ``Entry``
    
  103. instance ``entry``, assuming appropriate instances of ``Entry`` and ``Blog``
    
  104. are already saved to the database (so we can retrieve them below)::
    
  105. 
    
  106.     >>> from blog.models import Blog, Entry
    
  107.     >>> entry = Entry.objects.get(pk=1)
    
  108.     >>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
    
  109.     >>> entry.blog = cheese_blog
    
  110.     >>> entry.save()
    
  111. 
    
  112. Updating a :class:`~django.db.models.ManyToManyField` works a little
    
  113. differently -- use the
    
  114. :meth:`~django.db.models.fields.related.RelatedManager.add` method on the field
    
  115. to add a record to the relation. This example adds the ``Author`` instance
    
  116. ``joe`` to the ``entry`` object::
    
  117. 
    
  118.     >>> from blog.models import Author
    
  119.     >>> joe = Author.objects.create(name="Joe")
    
  120.     >>> entry.authors.add(joe)
    
  121. 
    
  122. To add multiple records to a :class:`~django.db.models.ManyToManyField` in one
    
  123. go, include multiple arguments in the call to
    
  124. :meth:`~django.db.models.fields.related.RelatedManager.add`, like this::
    
  125. 
    
  126.     >>> john = Author.objects.create(name="John")
    
  127.     >>> paul = Author.objects.create(name="Paul")
    
  128.     >>> george = Author.objects.create(name="George")
    
  129.     >>> ringo = Author.objects.create(name="Ringo")
    
  130.     >>> entry.authors.add(john, paul, george, ringo)
    
  131. 
    
  132. Django will complain if you try to assign or add an object of the wrong type.
    
  133. 
    
  134. .. _retrieving-objects:
    
  135. 
    
  136. Retrieving objects
    
  137. ==================
    
  138. 
    
  139. To retrieve objects from your database, construct a
    
  140. :class:`~django.db.models.query.QuerySet` via a
    
  141. :class:`~django.db.models.Manager` on your model class.
    
  142. 
    
  143. A :class:`~django.db.models.query.QuerySet` represents a collection of objects
    
  144. from your database. It can have zero, one or many *filters*. Filters narrow
    
  145. down the query results based on the given parameters. In SQL terms, a
    
  146. :class:`~django.db.models.query.QuerySet` equates to a ``SELECT`` statement,
    
  147. and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
    
  148. 
    
  149. You get a :class:`~django.db.models.query.QuerySet` by using your model's
    
  150. :class:`~django.db.models.Manager`. Each model has at least one
    
  151. :class:`~django.db.models.Manager`, and it's called
    
  152. :attr:`~django.db.models.Model.objects` by default. Access it directly via the
    
  153. model class, like so::
    
  154. 
    
  155.     >>> Blog.objects
    
  156.     <django.db.models.manager.Manager object at ...>
    
  157.     >>> b = Blog(name='Foo', tagline='Bar')
    
  158.     >>> b.objects
    
  159.     Traceback:
    
  160.         ...
    
  161.     AttributeError: "Manager isn't accessible via Blog instances."
    
  162. 
    
  163. .. note::
    
  164. 
    
  165.     ``Managers`` are accessible only via model classes, rather than from model
    
  166.     instances, to enforce a separation between "table-level" operations and
    
  167.     "record-level" operations.
    
  168. 
    
  169. The :class:`~django.db.models.Manager` is the main source of ``QuerySets`` for
    
  170. a model. For example, ``Blog.objects.all()`` returns a
    
  171. :class:`~django.db.models.query.QuerySet` that contains all ``Blog`` objects in
    
  172. the database.
    
  173. 
    
  174. Retrieving all objects
    
  175. ----------------------
    
  176. 
    
  177. The simplest way to retrieve objects from a table is to get all of them. To do
    
  178. this, use the :meth:`~django.db.models.query.QuerySet.all` method on a
    
  179. :class:`~django.db.models.Manager`::
    
  180. 
    
  181.     >>> all_entries = Entry.objects.all()
    
  182. 
    
  183. The :meth:`~django.db.models.query.QuerySet.all` method returns a
    
  184. :class:`~django.db.models.query.QuerySet` of all the objects in the database.
    
  185. 
    
  186. Retrieving specific objects with filters
    
  187. ----------------------------------------
    
  188. 
    
  189. The :class:`~django.db.models.query.QuerySet` returned by
    
  190. :meth:`~django.db.models.query.QuerySet.all` describes all objects in the
    
  191. database table. Usually, though, you'll need to select only a subset of the
    
  192. complete set of objects.
    
  193. 
    
  194. To create such a subset, you refine the initial
    
  195. :class:`~django.db.models.query.QuerySet`, adding filter conditions. The two
    
  196. most common ways to refine a :class:`~django.db.models.query.QuerySet` are:
    
  197. 
    
  198. ``filter(**kwargs)``
    
  199.     Returns a new :class:`~django.db.models.query.QuerySet` containing objects
    
  200.     that match the given lookup parameters.
    
  201. 
    
  202. ``exclude(**kwargs)``
    
  203.     Returns a new :class:`~django.db.models.query.QuerySet` containing objects
    
  204.     that do *not* match the given lookup parameters.
    
  205. 
    
  206. The lookup parameters (``**kwargs`` in the above function definitions) should
    
  207. be in the format described in `Field lookups`_ below.
    
  208. 
    
  209. For example, to get a :class:`~django.db.models.query.QuerySet` of blog entries
    
  210. from the year 2006, use :meth:`~django.db.models.query.QuerySet.filter` like
    
  211. so::
    
  212. 
    
  213.     Entry.objects.filter(pub_date__year=2006)
    
  214. 
    
  215. With the default manager class, it is the same as::
    
  216. 
    
  217.     Entry.objects.all().filter(pub_date__year=2006)
    
  218. 
    
  219. .. _chaining-filters:
    
  220. 
    
  221. Chaining filters
    
  222. ~~~~~~~~~~~~~~~~
    
  223. 
    
  224. The result of refining a :class:`~django.db.models.query.QuerySet` is itself a
    
  225. :class:`~django.db.models.query.QuerySet`, so it's possible to chain
    
  226. refinements together. For example::
    
  227. 
    
  228.     >>> Entry.objects.filter(
    
  229.     ...     headline__startswith='What'
    
  230.     ... ).exclude(
    
  231.     ...     pub_date__gte=datetime.date.today()
    
  232.     ... ).filter(
    
  233.     ...     pub_date__gte=datetime.date(2005, 1, 30)
    
  234.     ... )
    
  235. 
    
  236. This takes the initial :class:`~django.db.models.query.QuerySet` of all entries
    
  237. in the database, adds a filter, then an exclusion, then another filter. The
    
  238. final result is a :class:`~django.db.models.query.QuerySet` containing all
    
  239. entries with a headline that starts with "What", that were published between
    
  240. January 30, 2005, and the current day.
    
  241. 
    
  242. .. _filtered-querysets-are-unique:
    
  243. 
    
  244. Filtered ``QuerySet``\s are unique
    
  245. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  246. 
    
  247. Each time you refine a :class:`~django.db.models.query.QuerySet`, you get a
    
  248. brand-new :class:`~django.db.models.query.QuerySet` that is in no way bound to
    
  249. the previous :class:`~django.db.models.query.QuerySet`. Each refinement creates
    
  250. a separate and distinct :class:`~django.db.models.query.QuerySet` that can be
    
  251. stored, used and reused.
    
  252. 
    
  253. Example::
    
  254. 
    
  255.     >>> q1 = Entry.objects.filter(headline__startswith="What")
    
  256.     >>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
    
  257.     >>> q3 = q1.filter(pub_date__gte=datetime.date.today())
    
  258. 
    
  259. These three ``QuerySets`` are separate. The first is a base
    
  260. :class:`~django.db.models.query.QuerySet` containing all entries that contain a
    
  261. headline starting with "What". The second is a subset of the first, with an
    
  262. additional criteria that excludes records whose ``pub_date`` is today or in the
    
  263. future. The third is a subset of the first, with an additional criteria that
    
  264. selects only the records whose ``pub_date`` is today or in the future. The
    
  265. initial :class:`~django.db.models.query.QuerySet` (``q1``) is unaffected by the
    
  266. refinement process.
    
  267. 
    
  268. .. _querysets-are-lazy:
    
  269. 
    
  270. ``QuerySet``\s are lazy
    
  271. ~~~~~~~~~~~~~~~~~~~~~~~
    
  272. 
    
  273. ``QuerySets`` are lazy -- the act of creating a
    
  274. :class:`~django.db.models.query.QuerySet` doesn't involve any database
    
  275. activity. You can stack filters together all day long, and Django won't
    
  276. actually run the query until the :class:`~django.db.models.query.QuerySet` is
    
  277. *evaluated*. Take a look at this example::
    
  278. 
    
  279.     >>> q = Entry.objects.filter(headline__startswith="What")
    
  280.     >>> q = q.filter(pub_date__lte=datetime.date.today())
    
  281.     >>> q = q.exclude(body_text__icontains="food")
    
  282.     >>> print(q)
    
  283. 
    
  284. Though this looks like three database hits, in fact it hits the database only
    
  285. once, at the last line (``print(q)``). In general, the results of a
    
  286. :class:`~django.db.models.query.QuerySet` aren't fetched from the database
    
  287. until you "ask" for them. When you do, the
    
  288. :class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the
    
  289. database. For more details on exactly when evaluation takes place, see
    
  290. :ref:`when-querysets-are-evaluated`.
    
  291. 
    
  292. .. _retrieving-single-object-with-get:
    
  293. 
    
  294. Retrieving a single object with ``get()``
    
  295. -----------------------------------------
    
  296. 
    
  297. :meth:`~django.db.models.query.QuerySet.filter` will always give you a
    
  298. :class:`~django.db.models.query.QuerySet`, even if only a single object matches
    
  299. the query - in this case, it will be a
    
  300. :class:`~django.db.models.query.QuerySet` containing a single element.
    
  301. 
    
  302. If you know there is only one object that matches your query, you can use the
    
  303. :meth:`~django.db.models.query.QuerySet.get` method on a
    
  304. :class:`~django.db.models.Manager` which returns the object directly::
    
  305. 
    
  306.     >>> one_entry = Entry.objects.get(pk=1)
    
  307. 
    
  308. You can use any query expression with
    
  309. :meth:`~django.db.models.query.QuerySet.get`, just like with
    
  310. :meth:`~django.db.models.query.QuerySet.filter` - again, see `Field lookups`_
    
  311. below.
    
  312. 
    
  313. Note that there is a difference between using
    
  314. :meth:`~django.db.models.query.QuerySet.get`, and using
    
  315. :meth:`~django.db.models.query.QuerySet.filter` with a slice of ``[0]``. If
    
  316. there are no results that match the query,
    
  317. :meth:`~django.db.models.query.QuerySet.get` will raise a ``DoesNotExist``
    
  318. exception. This exception is an attribute of the model class that the query is
    
  319. being performed on - so in the code above, if there is no ``Entry`` object with
    
  320. a primary key of 1, Django will raise ``Entry.DoesNotExist``.
    
  321. 
    
  322. Similarly, Django will complain if more than one item matches the
    
  323. :meth:`~django.db.models.query.QuerySet.get` query. In this case, it will raise
    
  324. :exc:`~django.core.exceptions.MultipleObjectsReturned`, which again is an
    
  325. attribute of the model class itself.
    
  326. 
    
  327. 
    
  328. Other ``QuerySet`` methods
    
  329. --------------------------
    
  330. 
    
  331. Most of the time you'll use :meth:`~django.db.models.query.QuerySet.all`,
    
  332. :meth:`~django.db.models.query.QuerySet.get`,
    
  333. :meth:`~django.db.models.query.QuerySet.filter` and
    
  334. :meth:`~django.db.models.query.QuerySet.exclude` when you need to look up
    
  335. objects from the database. However, that's far from all there is; see the
    
  336. :ref:`QuerySet API Reference <queryset-api>` for a complete list of all the
    
  337. various :class:`~django.db.models.query.QuerySet` methods.
    
  338. 
    
  339. .. _limiting-querysets:
    
  340. 
    
  341. Limiting ``QuerySet``\s
    
  342. -----------------------
    
  343. 
    
  344. Use a subset of Python's array-slicing syntax to limit your
    
  345. :class:`~django.db.models.query.QuerySet` to a certain number of results. This
    
  346. is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
    
  347. 
    
  348. For example, this returns the first 5 objects (``LIMIT 5``)::
    
  349. 
    
  350.     >>> Entry.objects.all()[:5]
    
  351. 
    
  352. This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
    
  353. 
    
  354.     >>> Entry.objects.all()[5:10]
    
  355. 
    
  356. Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported.
    
  357. 
    
  358. Generally, slicing a :class:`~django.db.models.query.QuerySet` returns a new
    
  359. :class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An
    
  360. exception is if you use the "step" parameter of Python slice syntax. For
    
  361. example, this would actually execute the query in order to return a list of
    
  362. every *second* object of the first 10::
    
  363. 
    
  364.     >>> Entry.objects.all()[:10:2]
    
  365. 
    
  366. Further filtering or ordering of a sliced queryset is prohibited due to the
    
  367. ambiguous nature of how that might work.
    
  368. 
    
  369. To retrieve a *single* object rather than a list
    
  370. (e.g. ``SELECT foo FROM bar LIMIT 1``), use an index instead of a slice. For
    
  371. example, this returns the first ``Entry`` in the database, after ordering
    
  372. entries alphabetically by headline::
    
  373. 
    
  374.     >>> Entry.objects.order_by('headline')[0]
    
  375. 
    
  376. This is roughly equivalent to::
    
  377. 
    
  378.     >>> Entry.objects.order_by('headline')[0:1].get()
    
  379. 
    
  380. Note, however, that the first of these will raise ``IndexError`` while the
    
  381. second will raise ``DoesNotExist`` if no objects match the given criteria. See
    
  382. :meth:`~django.db.models.query.QuerySet.get` for more details.
    
  383. 
    
  384. .. _field-lookups-intro:
    
  385. 
    
  386. Field lookups
    
  387. -------------
    
  388. 
    
  389. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
    
  390. specified as keyword arguments to the :class:`~django.db.models.query.QuerySet`
    
  391. methods :meth:`~django.db.models.query.QuerySet.filter`,
    
  392. :meth:`~django.db.models.query.QuerySet.exclude` and
    
  393. :meth:`~django.db.models.query.QuerySet.get`.
    
  394. 
    
  395. Basic lookups keyword arguments take the form ``field__lookuptype=value``.
    
  396. (That's a double-underscore). For example::
    
  397. 
    
  398.     >>> Entry.objects.filter(pub_date__lte='2006-01-01')
    
  399. 
    
  400. translates (roughly) into the following SQL:
    
  401. 
    
  402. .. code-block:: sql
    
  403. 
    
  404.     SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
    
  405. 
    
  406. .. admonition:: How this is possible
    
  407. 
    
  408.    Python has the ability to define functions that accept arbitrary name-value
    
  409.    arguments whose names and values are evaluated at runtime. For more
    
  410.    information, see :ref:`tut-keywordargs` in the official Python tutorial.
    
  411. 
    
  412. The field specified in a lookup has to be the name of a model field. There's
    
  413. one exception though, in case of a :class:`~django.db.models.ForeignKey` you
    
  414. can specify the field name suffixed with ``_id``. In this case, the value
    
  415. parameter is expected to contain the raw value of the foreign model's primary
    
  416. key. For example:
    
  417. 
    
  418.     >>> Entry.objects.filter(blog_id=4)
    
  419. 
    
  420. If you pass an invalid keyword argument, a lookup function will raise
    
  421. ``TypeError``.
    
  422. 
    
  423. The database API supports about two dozen lookup types; a complete reference
    
  424. can be found in the :ref:`field lookup reference <field-lookups>`. To give you
    
  425. a taste of what's available, here's some of the more common lookups you'll
    
  426. probably use:
    
  427. 
    
  428. :lookup:`exact`
    
  429.     An "exact" match. For example::
    
  430. 
    
  431.         >>> Entry.objects.get(headline__exact="Cat bites dog")
    
  432. 
    
  433.     Would generate SQL along these lines:
    
  434. 
    
  435.     .. code-block:: sql
    
  436. 
    
  437.         SELECT ... WHERE headline = 'Cat bites dog';
    
  438. 
    
  439.     If you don't provide a lookup type -- that is, if your keyword argument
    
  440.     doesn't contain a double underscore -- the lookup type is assumed to be
    
  441.     ``exact``.
    
  442. 
    
  443.     For example, the following two statements are equivalent::
    
  444. 
    
  445.         >>> Blog.objects.get(id__exact=14)  # Explicit form
    
  446.         >>> Blog.objects.get(id=14)         # __exact is implied
    
  447. 
    
  448.     This is for convenience, because ``exact`` lookups are the common case.
    
  449. 
    
  450. :lookup:`iexact`
    
  451.     A case-insensitive match. So, the query::
    
  452. 
    
  453.         >>> Blog.objects.get(name__iexact="beatles blog")
    
  454. 
    
  455.     Would match a ``Blog`` titled ``"Beatles Blog"``, ``"beatles blog"``, or
    
  456.     even ``"BeAtlES blOG"``.
    
  457. 
    
  458. :lookup:`contains`
    
  459.     Case-sensitive containment test. For example::
    
  460. 
    
  461.         Entry.objects.get(headline__contains='Lennon')
    
  462. 
    
  463.     Roughly translates to this SQL:
    
  464. 
    
  465.     .. code-block:: sql
    
  466. 
    
  467.         SELECT ... WHERE headline LIKE '%Lennon%';
    
  468. 
    
  469.     Note this will match the headline ``'Today Lennon honored'`` but not
    
  470.     ``'today lennon honored'``.
    
  471. 
    
  472.     There's also a case-insensitive version, :lookup:`icontains`.
    
  473. 
    
  474. :lookup:`startswith`, :lookup:`endswith`
    
  475.     Starts-with and ends-with search, respectively. There are also
    
  476.     case-insensitive versions called :lookup:`istartswith` and
    
  477.     :lookup:`iendswith`.
    
  478. 
    
  479. Again, this only scratches the surface. A complete reference can be found in the
    
  480. :ref:`field lookup reference <field-lookups>`.
    
  481. 
    
  482. .. _lookups-that-span-relationships:
    
  483. 
    
  484. Lookups that span relationships
    
  485. -------------------------------
    
  486. 
    
  487. Django offers a powerful and intuitive way to "follow" relationships in
    
  488. lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
    
  489. scenes. To span a relationship, use the field name of related fields
    
  490. across models, separated by double underscores, until you get to the field you
    
  491. want.
    
  492. 
    
  493. This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
    
  494. is ``'Beatles Blog'``::
    
  495. 
    
  496.     >>> Entry.objects.filter(blog__name='Beatles Blog')
    
  497. 
    
  498. This spanning can be as deep as you'd like.
    
  499. 
    
  500. It works backwards, too. While it :attr:`can be customized
    
  501. <.ForeignKey.related_query_name>`, by default you refer to a "reverse"
    
  502. relationship in a lookup using the lowercase name of the model.
    
  503. 
    
  504. This example retrieves all ``Blog`` objects which have at least one ``Entry``
    
  505. whose ``headline`` contains ``'Lennon'``::
    
  506. 
    
  507.     >>> Blog.objects.filter(entry__headline__contains='Lennon')
    
  508. 
    
  509. If you are filtering across multiple relationships and one of the intermediate
    
  510. models doesn't have a value that meets the filter condition, Django will treat
    
  511. it as if there is an empty (all values are ``NULL``), but valid, object there.
    
  512. All this means is that no error will be raised. For example, in this filter::
    
  513. 
    
  514.     Blog.objects.filter(entry__authors__name='Lennon')
    
  515. 
    
  516. (if there was a related ``Author`` model), if there was no ``author``
    
  517. associated with an entry, it would be treated as if there was also no ``name``
    
  518. attached, rather than raising an error because of the missing ``author``.
    
  519. Usually this is exactly what you want to have happen. The only case where it
    
  520. might be confusing is if you are using :lookup:`isnull`. Thus::
    
  521. 
    
  522.     Blog.objects.filter(entry__authors__name__isnull=True)
    
  523. 
    
  524. will return ``Blog`` objects that have an empty ``name`` on the ``author`` and
    
  525. also those which have an empty ``author`` on the ``entry``. If you don't want
    
  526. those latter objects, you could write::
    
  527. 
    
  528.     Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
    
  529. 
    
  530. .. _spanning-multi-valued-relationships:
    
  531. 
    
  532. Spanning multi-valued relationships
    
  533. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  534. 
    
  535. When spanning a :class:`~django.db.models.ManyToManyField` or a reverse
    
  536. :class:`~django.db.models.ForeignKey` (such as from ``Blog`` to ``Entry``),
    
  537. filtering on multiple attributes raises the question of whether to require each
    
  538. attribute to coincide in the same related object. We might seek blogs that have
    
  539. an entry from 2008 with *“Lennon”* in its headline, or we might seek blogs that
    
  540. merely have any entry from 2008 as well as some newer or older entry with
    
  541. *“Lennon”* in its headline.
    
  542. 
    
  543. To select all blogs containing at least one entry from 2008 having *"Lennon"*
    
  544. in its headline (the same entry satisfying both conditions), we would write::
    
  545. 
    
  546.     Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
    
  547. 
    
  548. Otherwise, to perform a more permissive query selecting any blogs with merely
    
  549. *some* entry with *"Lennon"* in its headline and *some* entry from 2008, we
    
  550. would write::
    
  551. 
    
  552.     Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
    
  553. 
    
  554. Suppose there is only one blog that has both entries containing *"Lennon"* and
    
  555. entries from 2008, but that none of the entries from 2008 contained *"Lennon"*.
    
  556. The first query would not return any blogs, but the second query would return
    
  557. that one blog. (This is because the entries selected by the second filter may
    
  558. or may not be the same as the entries in the first filter. We are filtering the
    
  559. ``Blog`` items with each filter statement, not the ``Entry`` items.) In short,
    
  560. if each condition needs to match the same related object, then each should be
    
  561. contained in a single :meth:`~django.db.models.query.QuerySet.filter` call.
    
  562. 
    
  563. .. note::
    
  564. 
    
  565.     As the second (more permissive) query chains multiple filters, it performs
    
  566.     multiple joins to the primary model, potentially yielding duplicates.
    
  567. 
    
  568.         >>> from datetime import date
    
  569.         >>> beatles = Blog.objects.create(name='Beatles Blog')
    
  570.         >>> pop = Blog.objects.create(name='Pop Music Blog')
    
  571.         >>> Entry.objects.create(
    
  572.         ...     blog=beatles,
    
  573.         ...     headline='New Lennon Biography',
    
  574.         ...     pub_date=date(2008, 6, 1),
    
  575.         ... )
    
  576.         <Entry: New Lennon Biography>
    
  577.         >>> Entry.objects.create(
    
  578.         ...     blog=beatles,
    
  579.         ...     headline='New Lennon Biography in Paperback',
    
  580.         ...     pub_date=date(2009, 6, 1),
    
  581.         ... )
    
  582.         <Entry: New Lennon Biography in Paperback>
    
  583.         >>> Entry.objects.create(
    
  584.         ...     blog=pop,
    
  585.         ...     headline='Best Albums of 2008',
    
  586.         ...     pub_date=date(2008, 12, 15),
    
  587.         ... )
    
  588.         <Entry: Best Albums of 2008>
    
  589.         >>> Entry.objects.create(
    
  590.         ...     blog=pop,
    
  591.         ...     headline='Lennon Would Have Loved Hip Hop',
    
  592.         ...     pub_date=date(2020, 4, 1),
    
  593.         ... )
    
  594.         <Entry: Lennon Would Have Loved Hip Hop>
    
  595.         >>> Blog.objects.filter(
    
  596.         ...     entry__headline__contains='Lennon',
    
  597.         ...     entry__pub_date__year=2008,
    
  598.         ... )
    
  599.         <QuerySet [<Blog: Beatles Blog>]>
    
  600.         >>> Blog.objects.filter(
    
  601.         ...     entry__headline__contains='Lennon',
    
  602.         ... ).filter(
    
  603.         ...     entry__pub_date__year=2008,
    
  604.         ... )
    
  605.         <QuerySet [<Blog: Beatles Blog>, <Blog: Beatles Blog>, <Blog: Pop Music Blog]>
    
  606. 
    
  607. .. note::
    
  608. 
    
  609.     The behavior of :meth:`~django.db.models.query.QuerySet.filter` for queries
    
  610.     that span multi-value relationships, as described above, is not implemented
    
  611.     equivalently for :meth:`~django.db.models.query.QuerySet.exclude`. Instead,
    
  612.     the conditions in a single :meth:`~django.db.models.query.QuerySet.exclude`
    
  613.     call will not necessarily refer to the same item.
    
  614. 
    
  615.     For example, the following query would exclude blogs that contain *both*
    
  616.     entries with *"Lennon"* in the headline *and* entries published in 2008::
    
  617. 
    
  618.         Blog.objects.exclude(
    
  619.             entry__headline__contains='Lennon',
    
  620.             entry__pub_date__year=2008,
    
  621.         )
    
  622. 
    
  623.     However, unlike the behavior when using
    
  624.     :meth:`~django.db.models.query.QuerySet.filter`, this will not limit blogs
    
  625.     based on entries that satisfy both conditions. In order to do that, i.e.
    
  626.     to select all blogs that do not contain entries published with *"Lennon"*
    
  627.     that were published in 2008, you need to make two queries::
    
  628. 
    
  629.         Blog.objects.exclude(
    
  630.             entry__in=Entry.objects.filter(
    
  631.                 headline__contains='Lennon',
    
  632.                 pub_date__year=2008,
    
  633.             ),
    
  634.         )
    
  635. 
    
  636. .. _using-f-expressions-in-filters:
    
  637. 
    
  638. Filters can reference fields on the model
    
  639. -----------------------------------------
    
  640. 
    
  641. In the examples given so far, we have constructed filters that compare
    
  642. the value of a model field with a constant. But what if you want to compare
    
  643. the value of a model field with another field on the same model?
    
  644. 
    
  645. Django provides :class:`F expressions <django.db.models.F>` to allow such
    
  646. comparisons. Instances of ``F()`` act as a reference to a model field within a
    
  647. query. These references can then be used in query filters to compare the values
    
  648. of two different fields on the same model instance.
    
  649. 
    
  650. For example, to find a list of all blog entries that have had more comments
    
  651. than pingbacks, we construct an ``F()`` object to reference the pingback count,
    
  652. and use that ``F()`` object in the query::
    
  653. 
    
  654.     >>> from django.db.models import F
    
  655.     >>> Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks'))
    
  656. 
    
  657. Django supports the use of addition, subtraction, multiplication,
    
  658. division, modulo, and power arithmetic with ``F()`` objects, both with constants
    
  659. and with other ``F()`` objects. To find all the blog entries with more than
    
  660. *twice* as many comments as pingbacks, we modify the query::
    
  661. 
    
  662.     >>> Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks') * 2)
    
  663. 
    
  664. To find all the entries where the rating of the entry is less than the
    
  665. sum of the pingback count and comment count, we would issue the
    
  666. query::
    
  667. 
    
  668.     >>> Entry.objects.filter(rating__lt=F('number_of_comments') + F('number_of_pingbacks'))
    
  669. 
    
  670. You can also use the double underscore notation to span relationships in
    
  671. an ``F()`` object. An ``F()`` object with a double underscore will introduce
    
  672. any joins needed to access the related object. For example, to retrieve all
    
  673. the entries where the author's name is the same as the blog name, we could
    
  674. issue the query::
    
  675. 
    
  676.     >>> Entry.objects.filter(authors__name=F('blog__name'))
    
  677. 
    
  678. For date and date/time fields, you can add or subtract a
    
  679. :class:`~datetime.timedelta` object. The following would return all entries
    
  680. that were modified more than 3 days after they were published::
    
  681. 
    
  682.     >>> from datetime import timedelta
    
  683.     >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
    
  684. 
    
  685. The ``F()`` objects support bitwise operations by ``.bitand()``, ``.bitor()``,
    
  686. ``.bitxor()``, ``.bitrightshift()``, and ``.bitleftshift()``. For example::
    
  687. 
    
  688.     >>> F('somefield').bitand(16)
    
  689. 
    
  690. .. admonition:: Oracle
    
  691. 
    
  692.     Oracle doesn't support bitwise XOR operation.
    
  693. 
    
  694. .. _using-transforms-in-expressions:
    
  695. 
    
  696. Expressions can reference transforms
    
  697. ------------------------------------
    
  698. 
    
  699. Django supports using transforms in expressions.
    
  700. 
    
  701. For example, to find all ``Entry`` objects published in the same year as they
    
  702. were last modified::
    
  703. 
    
  704.     >>> from django.db.models import F
    
  705.     >>> Entry.objects.filter(pub_date__year=F('mod_date__year'))
    
  706. 
    
  707. To find the earliest year an entry was published, we can issue the query::
    
  708. 
    
  709.     >>> from django.db.models import Min
    
  710.     >>> Entry.objects.aggregate(first_published_year=Min('pub_date__year'))
    
  711. 
    
  712. This example finds the value of the highest rated entry and the total number
    
  713. of comments on all entries for each year::
    
  714. 
    
  715.     >>> from django.db.models import OuterRef, Subquery, Sum
    
  716.     >>> Entry.objects.values('pub_date__year').annotate(
    
  717.     ...     top_rating=Subquery(
    
  718.     ...         Entry.objects.filter(
    
  719.     ...             pub_date__year=OuterRef('pub_date__year'),
    
  720.     ...         ).order_by('-rating').values('rating')[:1]
    
  721.     ...     ),
    
  722.     ...     total_comments=Sum('number_of_comments'),
    
  723.     ... )
    
  724. 
    
  725. The ``pk`` lookup shortcut
    
  726. --------------------------
    
  727. 
    
  728. For convenience, Django provides a ``pk`` lookup shortcut, which stands for
    
  729. "primary key".
    
  730. 
    
  731. In the example ``Blog`` model, the primary key is the ``id`` field, so these
    
  732. three statements are equivalent::
    
  733. 
    
  734.     >>> Blog.objects.get(id__exact=14) # Explicit form
    
  735.     >>> Blog.objects.get(id=14) # __exact is implied
    
  736.     >>> Blog.objects.get(pk=14) # pk implies id__exact
    
  737. 
    
  738. The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
    
  739. can be combined with ``pk`` to perform a query on the primary key of a model::
    
  740. 
    
  741.     # Get blogs entries with id 1, 4 and 7
    
  742.     >>> Blog.objects.filter(pk__in=[1,4,7])
    
  743. 
    
  744.     # Get all blog entries with id > 14
    
  745.     >>> Blog.objects.filter(pk__gt=14)
    
  746. 
    
  747. ``pk`` lookups also work across joins. For example, these three statements are
    
  748. equivalent::
    
  749. 
    
  750.     >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
    
  751.     >>> Entry.objects.filter(blog__id=3)        # __exact is implied
    
  752.     >>> Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact
    
  753. 
    
  754. Escaping percent signs and underscores in ``LIKE`` statements
    
  755. -------------------------------------------------------------
    
  756. 
    
  757. The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
    
  758. ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
    
  759. and ``iendswith``) will automatically escape the two special characters used in
    
  760. ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
    
  761. statement, the percent sign signifies a multiple-character wildcard and the
    
  762. underscore signifies a single-character wildcard.)
    
  763. 
    
  764. This means things should work intuitively, so the abstraction doesn't leak.
    
  765. For example, to retrieve all the entries that contain a percent sign, use the
    
  766. percent sign as any other character::
    
  767. 
    
  768.     >>> Entry.objects.filter(headline__contains='%')
    
  769. 
    
  770. Django takes care of the quoting for you; the resulting SQL will look something
    
  771. like this:
    
  772. 
    
  773. .. code-block:: sql
    
  774. 
    
  775.     SELECT ... WHERE headline LIKE '%\%%';
    
  776. 
    
  777. Same goes for underscores. Both percentage signs and underscores are handled
    
  778. for you transparently.
    
  779. 
    
  780. .. _caching-and-querysets:
    
  781. 
    
  782. Caching and ``QuerySet``\s
    
  783. --------------------------
    
  784. 
    
  785. Each :class:`~django.db.models.query.QuerySet` contains a cache to minimize
    
  786. database access. Understanding how it works will allow you to write the most
    
  787. efficient code.
    
  788. 
    
  789. In a newly created :class:`~django.db.models.query.QuerySet`, the cache is
    
  790. empty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated
    
  791. -- and, hence, a database query happens -- Django saves the query results in
    
  792. the :class:`~django.db.models.query.QuerySet`’s cache and returns the results
    
  793. that have been explicitly requested (e.g., the next element, if the
    
  794. :class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent
    
  795. evaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached
    
  796. results.
    
  797. 
    
  798. Keep this caching behavior in mind, because it may bite you if you don't use
    
  799. your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
    
  800. following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
    
  801. them, and throw them away::
    
  802. 
    
  803.     >>> print([e.headline for e in Entry.objects.all()])
    
  804.     >>> print([e.pub_date for e in Entry.objects.all()])
    
  805. 
    
  806. That means the same database query will be executed twice, effectively doubling
    
  807. your database load. Also, there's a possibility the two lists may not include
    
  808. the same database records, because an ``Entry`` may have been added or deleted
    
  809. in the split second between the two requests.
    
  810. 
    
  811. To avoid this problem, save the :class:`~django.db.models.query.QuerySet` and
    
  812. reuse it::
    
  813. 
    
  814.     >>> queryset = Entry.objects.all()
    
  815.     >>> print([p.headline for p in queryset]) # Evaluate the query set.
    
  816.     >>> print([p.pub_date for p in queryset]) # Reuse the cache from the evaluation.
    
  817. 
    
  818. When ``QuerySet``\s are not cached
    
  819. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  820. 
    
  821. Querysets do not always cache their results.  When evaluating only *part* of
    
  822. the queryset, the cache is checked, but if it is not populated then the items
    
  823. returned by the subsequent query are not cached. Specifically, this means that
    
  824. :ref:`limiting the queryset <limiting-querysets>` using an array slice or an
    
  825. index will not populate the cache.
    
  826. 
    
  827. For example, repeatedly getting a certain index in a queryset object will query
    
  828. the database each time::
    
  829. 
    
  830.     >>> queryset = Entry.objects.all()
    
  831.     >>> print(queryset[5]) # Queries the database
    
  832.     >>> print(queryset[5]) # Queries the database again
    
  833. 
    
  834. However, if the entire queryset has already been evaluated, the cache will be
    
  835. checked instead::
    
  836. 
    
  837.     >>> queryset = Entry.objects.all()
    
  838.     >>> [entry for entry in queryset] # Queries the database
    
  839.     >>> print(queryset[5]) # Uses cache
    
  840.     >>> print(queryset[5]) # Uses cache
    
  841. 
    
  842. Here are some examples of other actions that will result in the entire queryset
    
  843. being evaluated and therefore populate the cache::
    
  844. 
    
  845.     >>> [entry for entry in queryset]
    
  846.     >>> bool(queryset)
    
  847.     >>> entry in queryset
    
  848.     >>> list(queryset)
    
  849. 
    
  850. .. note::
    
  851. 
    
  852.     Simply printing the queryset will not populate the cache. This is because
    
  853.     the call to ``__repr__()`` only returns a slice of the entire queryset.
    
  854. 
    
  855. .. _async-queries:
    
  856. 
    
  857. Asynchronous queries
    
  858. ====================
    
  859. 
    
  860. .. versionadded:: 4.1
    
  861. 
    
  862. If you are writing asynchronous views or code, you cannot use the ORM for
    
  863. queries in quite the way we have described above, as you cannot call *blocking*
    
  864. synchronous code from asynchronous code - it will block up the event loop
    
  865. (or, more likely, Django will notice and raise a ``SynchronousOnlyOperation``
    
  866. to stop that from happening).
    
  867. 
    
  868. Fortunately, you can do many queries using Django's asynchronous query APIs.
    
  869. Every method that might block - such as ``get()`` or ``delete()`` - has an
    
  870. asynchronous variant (``aget()`` or ``adelete()``), and when you iterate over
    
  871. results, you can use asynchronous iteration (``async for``) instead.
    
  872. 
    
  873. Query iteration
    
  874. ---------------
    
  875. 
    
  876. .. versionadded:: 4.1
    
  877. 
    
  878. The default way of iterating over a query - with ``for`` - will result in a
    
  879. blocking database query behind the scenes as Django loads the results at
    
  880. iteration time. To fix this, you can swap to ``async for``::
    
  881. 
    
  882.     async for entry in Authors.objects.filter(name__startswith="A"):
    
  883.         ...
    
  884. 
    
  885. Be aware that you also can't do other things that might iterate over the
    
  886. queryset, such as wrapping ``list()`` around it to force its evaluation (you
    
  887. can use ``async for`` in a comprehension, if you want it).
    
  888. 
    
  889. Because ``QuerySet`` methods like ``filter()`` and ``exclude()`` do not
    
  890. actually run the query - they set up the queryset to run when it's iterated
    
  891. over - you can use those freely in asynchronous code. For a guide to which
    
  892. methods can keep being used like this, and which have asynchronous versions,
    
  893. read the next section.
    
  894. 
    
  895. ``QuerySet`` and manager methods
    
  896. --------------------------------
    
  897. 
    
  898. .. versionadded:: 4.1
    
  899. 
    
  900. Some methods on managers and querysets - like ``get()`` and ``first()`` - force
    
  901. execution of the queryset and are blocking. Some, like ``filter()`` and
    
  902. ``exclude()``, don't force execution and so are safe to run from asynchronous
    
  903. code. But how are you supposed to tell the difference?
    
  904. 
    
  905. While you could poke around and see if there is an ``a``-prefixed version of
    
  906. the method (for example, we have ``aget()`` but not ``afilter()``), there is a
    
  907. more logical way - look up what kind of method it is in the
    
  908. :doc:`QuerySet reference </ref/models/querysets>`.
    
  909. 
    
  910. In there, you'll find the methods on QuerySets grouped into two sections:
    
  911. 
    
  912. * *Methods that return new querysets*: These are the non-blocking ones,
    
  913.   and don't have asynchronous versions. You're free to use these in any
    
  914.   situation, though read the notes on ``defer()`` and ``only()`` before you use
    
  915.   them.
    
  916. 
    
  917. * *Methods that do not return querysets*: These are the blocking ones, and
    
  918.   have asynchronous versions - the asynchronous name for each is noted in its
    
  919.   documentation, though our standard pattern is to add an ``a`` prefix.
    
  920. 
    
  921. Using this distinction, you can work out when you need to use asynchronous
    
  922. versions, and when you don't. For example, here's a valid asynchronous query::
    
  923. 
    
  924.     user = await User.objects.filter(username=my_input).afirst()
    
  925. 
    
  926. ``filter()`` returns a queryset, and so it's fine to keep chaining it inside an
    
  927. asynchronous environment, whereas ``first()`` evaluates and returns a model
    
  928. instance - thus, we change to ``afirst()``, and use ``await`` at the front of
    
  929. the whole expression in order to call it in an asynchronous-friendly way.
    
  930. 
    
  931. .. note::
    
  932. 
    
  933.     If you forget to put the ``await`` part in, you may see errors like
    
  934.     *"coroutine object has no attribute x"* or *"<coroutine …>"* strings in
    
  935.     place of your model instances. If you ever see these, you are missing an
    
  936.     ``await`` somewhere to turn that coroutine into a real value.
    
  937. 
    
  938. Transactions
    
  939. ------------
    
  940. 
    
  941. .. versionadded:: 4.1
    
  942. 
    
  943. Transactions are **not** currently supported with asynchronous queries and
    
  944. updates. You will find that trying to use one raises
    
  945. ``SynchronousOnlyOperation``.
    
  946. 
    
  947. If you wish to use a transaction, we suggest you write your ORM code inside a
    
  948. separate, synchronous function and then call that using ``sync_to_async`` - see
    
  949. :doc:`/topics/async` for more.
    
  950. 
    
  951. .. _querying-jsonfield:
    
  952. 
    
  953. Querying ``JSONField``
    
  954. ======================
    
  955. 
    
  956. Lookups implementation is different in :class:`~django.db.models.JSONField`,
    
  957. mainly due to the existence of key transformations. To demonstrate, we will use
    
  958. the following example model::
    
  959. 
    
  960.     from django.db import models
    
  961. 
    
  962.     class Dog(models.Model):
    
  963.         name = models.CharField(max_length=200)
    
  964.         data = models.JSONField(null=True)
    
  965. 
    
  966.         def __str__(self):
    
  967.             return self.name
    
  968. 
    
  969. Storing and querying for ``None``
    
  970. ---------------------------------
    
  971. 
    
  972. As with other fields, storing ``None`` as the field's value will store it as
    
  973. SQL ``NULL``. While not recommended, it is possible to store JSON scalar
    
  974. ``null`` instead of SQL ``NULL`` by using :class:`Value('null')
    
  975. <django.db.models.Value>`.
    
  976. 
    
  977. Whichever of the values is stored, when retrieved from the database, the Python
    
  978. representation of the JSON scalar ``null`` is the same as SQL ``NULL``, i.e.
    
  979. ``None``. Therefore, it can be hard to distinguish between them.
    
  980. 
    
  981. This only applies to ``None`` as the top-level value of the field. If ``None``
    
  982. is inside a :py:class:`list` or :py:class:`dict`, it will always be interpreted
    
  983. as JSON ``null``.
    
  984. 
    
  985. When querying, ``None`` value will always be interpreted as JSON ``null``. To
    
  986. query for SQL ``NULL``, use :lookup:`isnull`::
    
  987. 
    
  988.     >>> Dog.objects.create(name='Max', data=None)  # SQL NULL.
    
  989.     <Dog: Max>
    
  990.     >>> Dog.objects.create(name='Archie', data=Value('null'))  # JSON null.
    
  991.     <Dog: Archie>
    
  992.     >>> Dog.objects.filter(data=None)
    
  993.     <QuerySet [<Dog: Archie>]>
    
  994.     >>> Dog.objects.filter(data=Value('null'))
    
  995.     <QuerySet [<Dog: Archie>]>
    
  996.     >>> Dog.objects.filter(data__isnull=True)
    
  997.     <QuerySet [<Dog: Max>]>
    
  998.     >>> Dog.objects.filter(data__isnull=False)
    
  999.     <QuerySet [<Dog: Archie>]>
    
  1000. 
    
  1001. Unless you are sure you wish to work with SQL ``NULL`` values, consider setting
    
  1002. ``null=False`` and providing a suitable default for empty values, such as
    
  1003. ``default=dict``.
    
  1004. 
    
  1005. .. note::
    
  1006. 
    
  1007.     Storing JSON scalar ``null`` does not violate :attr:`null=False
    
  1008.     <django.db.models.Field.null>`.
    
  1009. 
    
  1010. .. fieldlookup:: jsonfield.key
    
  1011. 
    
  1012. Key, index, and path transforms
    
  1013. -------------------------------
    
  1014. 
    
  1015. To query based on a given dictionary key, use that key as the lookup name::
    
  1016. 
    
  1017.     >>> Dog.objects.create(name='Rufus', data={
    
  1018.     ...     'breed': 'labrador',
    
  1019.     ...     'owner': {
    
  1020.     ...         'name': 'Bob',
    
  1021.     ...         'other_pets': [{
    
  1022.     ...             'name': 'Fishy',
    
  1023.     ...         }],
    
  1024.     ...     },
    
  1025.     ... })
    
  1026.     <Dog: Rufus>
    
  1027.     >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': None})
    
  1028.     <Dog: Meg>
    
  1029.     >>> Dog.objects.filter(data__breed='collie')
    
  1030.     <QuerySet [<Dog: Meg>]>
    
  1031. 
    
  1032. Multiple keys can be chained together to form a path lookup::
    
  1033. 
    
  1034.     >>> Dog.objects.filter(data__owner__name='Bob')
    
  1035.     <QuerySet [<Dog: Rufus>]>
    
  1036. 
    
  1037. If the key is an integer, it will be interpreted as an index transform in an
    
  1038. array::
    
  1039. 
    
  1040.     >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
    
  1041.     <QuerySet [<Dog: Rufus>]>
    
  1042. 
    
  1043. If the key you wish to query by clashes with the name of another lookup, use
    
  1044. the :lookup:`contains <jsonfield.contains>` lookup instead.
    
  1045. 
    
  1046. To query for missing keys, use the ``isnull`` lookup::
    
  1047. 
    
  1048.     >>> Dog.objects.create(name='Shep', data={'breed': 'collie'})
    
  1049.     <Dog: Shep>
    
  1050.     >>> Dog.objects.filter(data__owner__isnull=True)
    
  1051.     <QuerySet [<Dog: Shep>]>
    
  1052. 
    
  1053. .. note::
    
  1054. 
    
  1055.     The lookup examples given above implicitly use the :lookup:`exact` lookup.
    
  1056.     Key, index, and path transforms can also be chained with:
    
  1057.     :lookup:`icontains`, :lookup:`endswith`, :lookup:`iendswith`,
    
  1058.     :lookup:`iexact`, :lookup:`regex`, :lookup:`iregex`, :lookup:`startswith`,
    
  1059.     :lookup:`istartswith`, :lookup:`lt`, :lookup:`lte`, :lookup:`gt`, and
    
  1060.     :lookup:`gte`, as well as with :ref:`containment-and-key-lookups`.
    
  1061. 
    
  1062. .. note::
    
  1063. 
    
  1064.     Due to the way in which key-path queries work,
    
  1065.     :meth:`~django.db.models.query.QuerySet.exclude` and
    
  1066.     :meth:`~django.db.models.query.QuerySet.filter` are not guaranteed to
    
  1067.     produce exhaustive sets. If you want to include objects that do not have
    
  1068.     the path, add the ``isnull`` lookup.
    
  1069. 
    
  1070. .. warning::
    
  1071. 
    
  1072.     Since any string could be a key in a JSON object, any lookup other than
    
  1073.     those listed below will be interpreted as a key lookup. No errors are
    
  1074.     raised. Be extra careful for typing mistakes, and always check your queries
    
  1075.     work as you intend.
    
  1076. 
    
  1077. .. admonition:: MariaDB and Oracle users
    
  1078. 
    
  1079.     Using :meth:`~django.db.models.query.QuerySet.order_by` on key, index, or
    
  1080.     path transforms will sort the objects using the string representation of
    
  1081.     the values. This is because MariaDB and Oracle Database do not provide a
    
  1082.     function that converts JSON values into their equivalent SQL values.
    
  1083. 
    
  1084. .. admonition:: Oracle users
    
  1085. 
    
  1086.     On Oracle Database, using ``None`` as the lookup value in an
    
  1087.     :meth:`~django.db.models.query.QuerySet.exclude` query will return objects
    
  1088.     that do not have ``null`` as the value at the given path, including objects
    
  1089.     that do not have the path. On other database backends, the query will
    
  1090.     return objects that have the path and the value is not ``null``.
    
  1091. 
    
  1092. .. admonition:: PostgreSQL users
    
  1093. 
    
  1094.     On PostgreSQL, if only one key or index is used, the SQL operator ``->`` is
    
  1095.     used. If multiple operators are used then the ``#>`` operator is used.
    
  1096. 
    
  1097. .. admonition:: SQLite users
    
  1098. 
    
  1099.     On SQLite, ``"true"``, ``"false"``, and ``"null"`` string values will
    
  1100.     always be interpreted as ``True``, ``False``, and JSON ``null``
    
  1101.     respectively.
    
  1102. 
    
  1103. .. _containment-and-key-lookups:
    
  1104. 
    
  1105. Containment and key lookups
    
  1106. ---------------------------
    
  1107. 
    
  1108. .. fieldlookup:: jsonfield.contains
    
  1109. 
    
  1110. ``contains``
    
  1111. ~~~~~~~~~~~~
    
  1112. 
    
  1113. The :lookup:`contains` lookup is overridden on ``JSONField``. The returned
    
  1114. objects are those where the given ``dict`` of key-value pairs are all
    
  1115. contained in the top-level of the field. For example::
    
  1116. 
    
  1117.     >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
    
  1118.     <Dog: Rufus>
    
  1119.     >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
    
  1120.     <Dog: Meg>
    
  1121.     >>> Dog.objects.create(name='Fred', data={})
    
  1122.     <Dog: Fred>
    
  1123.     >>> Dog.objects.filter(data__contains={'owner': 'Bob'})
    
  1124.     <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
    
  1125.     >>> Dog.objects.filter(data__contains={'breed': 'collie'})
    
  1126.     <QuerySet [<Dog: Meg>]>
    
  1127. 
    
  1128. .. admonition:: Oracle and SQLite
    
  1129. 
    
  1130.     ``contains`` is not supported on Oracle and SQLite.
    
  1131. 
    
  1132. .. fieldlookup:: jsonfield.contained_by
    
  1133. 
    
  1134. ``contained_by``
    
  1135. ~~~~~~~~~~~~~~~~
    
  1136. 
    
  1137. This is the inverse of the :lookup:`contains <jsonfield.contains>` lookup - the
    
  1138. objects returned will be those where the key-value pairs on the object are a
    
  1139. subset of those in the value passed. For example::
    
  1140. 
    
  1141.     >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
    
  1142.     <Dog: Rufus>
    
  1143.     >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
    
  1144.     <Dog: Meg>
    
  1145.     >>> Dog.objects.create(name='Fred', data={})
    
  1146.     <Dog: Fred>
    
  1147.     >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})
    
  1148.     <QuerySet [<Dog: Meg>, <Dog: Fred>]>
    
  1149.     >>> Dog.objects.filter(data__contained_by={'breed': 'collie'})
    
  1150.     <QuerySet [<Dog: Fred>]>
    
  1151. 
    
  1152. .. admonition:: Oracle and SQLite
    
  1153. 
    
  1154.     ``contained_by`` is not supported on Oracle and SQLite.
    
  1155. 
    
  1156. .. fieldlookup:: jsonfield.has_key
    
  1157. 
    
  1158. ``has_key``
    
  1159. ~~~~~~~~~~~
    
  1160. 
    
  1161. Returns objects where the given key is in the top-level of the data. For
    
  1162. example::
    
  1163. 
    
  1164.     >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
    
  1165.     <Dog: Rufus>
    
  1166.     >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
    
  1167.     <Dog: Meg>
    
  1168.     >>> Dog.objects.filter(data__has_key='owner')
    
  1169.     <QuerySet [<Dog: Meg>]>
    
  1170. 
    
  1171. .. fieldlookup:: jsonfield.has_any_keys
    
  1172. 
    
  1173. ``has_keys``
    
  1174. ~~~~~~~~~~~~
    
  1175. 
    
  1176. Returns objects where all of the given keys are in the top-level of the data.
    
  1177. For example::
    
  1178. 
    
  1179.     >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
    
  1180.     <Dog: Rufus>
    
  1181.     >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
    
  1182.     <Dog: Meg>
    
  1183.     >>> Dog.objects.filter(data__has_keys=['breed', 'owner'])
    
  1184.     <QuerySet [<Dog: Meg>]>
    
  1185. 
    
  1186. .. fieldlookup:: jsonfield.has_keys
    
  1187. 
    
  1188. ``has_any_keys``
    
  1189. ~~~~~~~~~~~~~~~~
    
  1190. 
    
  1191. Returns objects where any of the given keys are in the top-level of the data.
    
  1192. For example::
    
  1193. 
    
  1194.     >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
    
  1195.     <Dog: Rufus>
    
  1196.     >>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
    
  1197.     <Dog: Meg>
    
  1198.     >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])
    
  1199.     <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
    
  1200. 
    
  1201. .. _complex-lookups-with-q:
    
  1202. 
    
  1203. Complex lookups with ``Q`` objects
    
  1204. ==================================
    
  1205. 
    
  1206. Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
    
  1207. etc. -- are "AND"ed together. If you need to execute more complex queries (for
    
  1208. example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.
    
  1209. 
    
  1210. A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object
    
  1211. used to encapsulate a collection of keyword arguments. These keyword arguments
    
  1212. are specified as in "Field lookups" above.
    
  1213. 
    
  1214. For example, this ``Q`` object encapsulates a single ``LIKE`` query::
    
  1215. 
    
  1216.     from django.db.models import Q
    
  1217.     Q(question__startswith='What')
    
  1218. 
    
  1219. ``Q`` objects can be combined using the ``&``, ``|``, and ``^`` operators. When
    
  1220. an operator is used on two ``Q`` objects, it yields a new ``Q`` object.
    
  1221. 
    
  1222. For example, this statement yields a single ``Q`` object that represents the
    
  1223. "OR" of two ``"question__startswith"`` queries::
    
  1224. 
    
  1225.     Q(question__startswith='Who') | Q(question__startswith='What')
    
  1226. 
    
  1227. This is equivalent to the following SQL ``WHERE`` clause::
    
  1228. 
    
  1229.     WHERE question LIKE 'Who%' OR question LIKE 'What%'
    
  1230. 
    
  1231. You can compose statements of arbitrary complexity by combining ``Q`` objects
    
  1232. with the ``&``, ``|``, and ``^`` operators and use parenthetical grouping.
    
  1233. Also, ``Q`` objects can be negated using the ``~`` operator, allowing for
    
  1234. combined lookups that combine both a normal query and a negated (``NOT``)
    
  1235. query::
    
  1236. 
    
  1237.     Q(question__startswith='Who') | ~Q(pub_date__year=2005)
    
  1238. 
    
  1239. Each lookup function that takes keyword-arguments
    
  1240. (e.g. :meth:`~django.db.models.query.QuerySet.filter`,
    
  1241. :meth:`~django.db.models.query.QuerySet.exclude`,
    
  1242. :meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more
    
  1243. ``Q`` objects as positional (not-named) arguments. If you provide multiple
    
  1244. ``Q`` object arguments to a lookup function, the arguments will be "AND"ed
    
  1245. together. For example::
    
  1246. 
    
  1247.     Poll.objects.get(
    
  1248.         Q(question__startswith='Who'),
    
  1249.         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    
  1250.     )
    
  1251. 
    
  1252. ... roughly translates into the SQL:
    
  1253. 
    
  1254. .. code-block:: sql
    
  1255. 
    
  1256.     SELECT * from polls WHERE question LIKE 'Who%'
    
  1257.         AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
    
  1258. 
    
  1259. Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
    
  1260. arguments provided to a lookup function (be they keyword arguments or ``Q``
    
  1261. objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
    
  1262. precede the definition of any keyword arguments. For example::
    
  1263. 
    
  1264.     Poll.objects.get(
    
  1265.         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    
  1266.         question__startswith='Who',
    
  1267.     )
    
  1268. 
    
  1269. ... would be a valid query, equivalent to the previous example; but::
    
  1270. 
    
  1271.     # INVALID QUERY
    
  1272.     Poll.objects.get(
    
  1273.         question__startswith='Who',
    
  1274.         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    
  1275.     )
    
  1276. 
    
  1277. ... would not be valid.
    
  1278. 
    
  1279. .. seealso::
    
  1280. 
    
  1281.     The :source:`OR lookups examples <tests/or_lookups/tests.py>` in Django's
    
  1282.     unit tests show some possible uses of ``Q``.
    
  1283. 
    
  1284. .. versionchanged:: 4.1
    
  1285. 
    
  1286.     Support for the ``^`` (``XOR``) operator was added.
    
  1287. 
    
  1288. Comparing objects
    
  1289. =================
    
  1290. 
    
  1291. To compare two model instances, use the standard Python comparison operator,
    
  1292. the double equals sign: ``==``. Behind the scenes, that compares the primary
    
  1293. key values of two models.
    
  1294. 
    
  1295. Using the ``Entry`` example above, the following two statements are equivalent::
    
  1296. 
    
  1297.     >>> some_entry == other_entry
    
  1298.     >>> some_entry.id == other_entry.id
    
  1299. 
    
  1300. If a model's primary key isn't called ``id``, no problem. Comparisons will
    
  1301. always use the primary key, whatever it's called. For example, if a model's
    
  1302. primary key field is called ``name``, these two statements are equivalent::
    
  1303. 
    
  1304.     >>> some_obj == other_obj
    
  1305.     >>> some_obj.name == other_obj.name
    
  1306. 
    
  1307. .. _topics-db-queries-delete:
    
  1308. 
    
  1309. Deleting objects
    
  1310. ================
    
  1311. 
    
  1312. The delete method, conveniently, is named
    
  1313. :meth:`~django.db.models.Model.delete`. This method immediately deletes the
    
  1314. object and returns the number of objects deleted and a dictionary with
    
  1315. the number of deletions per object type. Example::
    
  1316. 
    
  1317.     >>> e.delete()
    
  1318.     (1, {'blog.Entry': 1})
    
  1319. 
    
  1320. You can also delete objects in bulk. Every
    
  1321. :class:`~django.db.models.query.QuerySet` has a
    
  1322. :meth:`~django.db.models.query.QuerySet.delete` method, which deletes all
    
  1323. members of that :class:`~django.db.models.query.QuerySet`.
    
  1324. 
    
  1325. For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
    
  1326. 2005::
    
  1327. 
    
  1328.     >>> Entry.objects.filter(pub_date__year=2005).delete()
    
  1329.     (5, {'webapp.Entry': 5})
    
  1330. 
    
  1331. Keep in mind that this will, whenever possible, be executed purely in SQL, and
    
  1332. so the ``delete()`` methods of individual object instances will not necessarily
    
  1333. be called during the process. If you've provided a custom ``delete()`` method
    
  1334. on a model class and want to ensure that it is called, you will need to
    
  1335. "manually" delete instances of that model (e.g., by iterating over a
    
  1336. :class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each
    
  1337. object individually) rather than using the bulk
    
  1338. :meth:`~django.db.models.query.QuerySet.delete` method of a
    
  1339. :class:`~django.db.models.query.QuerySet`.
    
  1340. 
    
  1341. When Django deletes an object, by default it emulates the behavior of the SQL
    
  1342. constraint ``ON DELETE CASCADE`` -- in other words, any objects which had
    
  1343. foreign keys pointing at the object to be deleted will be deleted along with
    
  1344. it. For example::
    
  1345. 
    
  1346.     b = Blog.objects.get(pk=1)
    
  1347.     # This will delete the Blog and all of its Entry objects.
    
  1348.     b.delete()
    
  1349. 
    
  1350. This cascade behavior is customizable via the
    
  1351. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
    
  1352. :class:`~django.db.models.ForeignKey`.
    
  1353. 
    
  1354. Note that :meth:`~django.db.models.query.QuerySet.delete` is the only
    
  1355. :class:`~django.db.models.query.QuerySet` method that is not exposed on a
    
  1356. :class:`~django.db.models.Manager` itself. This is a safety mechanism to
    
  1357. prevent you from accidentally requesting ``Entry.objects.delete()``, and
    
  1358. deleting *all* the entries. If you *do* want to delete all the objects, then
    
  1359. you have to explicitly request a complete query set::
    
  1360. 
    
  1361.     Entry.objects.all().delete()
    
  1362. 
    
  1363. .. _topics-db-queries-copy:
    
  1364. 
    
  1365. Copying model instances
    
  1366. =======================
    
  1367. 
    
  1368. Although there is no built-in method for copying model instances, it is
    
  1369. possible to easily create new instance with all fields' values copied. In the
    
  1370. simplest case, you can set ``pk`` to ``None`` and
    
  1371. :attr:`_state.adding <django.db.models.Model._state>` to ``True``. Using our
    
  1372. blog example::
    
  1373. 
    
  1374.     blog = Blog(name='My blog', tagline='Blogging is easy')
    
  1375.     blog.save() # blog.pk == 1
    
  1376. 
    
  1377.     blog.pk = None
    
  1378.     blog._state.adding = True
    
  1379.     blog.save() # blog.pk == 2
    
  1380. 
    
  1381. Things get more complicated if you use inheritance. Consider a subclass of
    
  1382. ``Blog``::
    
  1383. 
    
  1384.     class ThemeBlog(Blog):
    
  1385.         theme = models.CharField(max_length=200)
    
  1386. 
    
  1387.     django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')
    
  1388.     django_blog.save() # django_blog.pk == 3
    
  1389. 
    
  1390. Due to how inheritance works, you have to set both ``pk`` and ``id`` to
    
  1391. ``None``, and ``_state.adding`` to ``True``::
    
  1392. 
    
  1393.     django_blog.pk = None
    
  1394.     django_blog.id = None
    
  1395.     django_blog._state.adding = True
    
  1396.     django_blog.save() # django_blog.pk == 4
    
  1397. 
    
  1398. This process doesn't copy relations that aren't part of the model's database
    
  1399. table. For example, ``Entry`` has a ``ManyToManyField`` to ``Author``. After
    
  1400. duplicating an entry, you must set the many-to-many relations for the new
    
  1401. entry::
    
  1402. 
    
  1403.     entry = Entry.objects.all()[0] # some previous entry
    
  1404.     old_authors = entry.authors.all()
    
  1405.     entry.pk = None
    
  1406.     entry._state.adding = True
    
  1407.     entry.save()
    
  1408.     entry.authors.set(old_authors)
    
  1409. 
    
  1410. For a ``OneToOneField``, you must duplicate the related object and assign it
    
  1411. to the new object's field to avoid violating the one-to-one unique constraint.
    
  1412. For example, assuming ``entry`` is already duplicated as above::
    
  1413. 
    
  1414.     detail = EntryDetail.objects.all()[0]
    
  1415.     detail.pk = None
    
  1416.     detail._state.adding = True
    
  1417.     detail.entry = entry
    
  1418.     detail.save()
    
  1419. 
    
  1420. .. _topics-db-queries-update:
    
  1421. 
    
  1422. Updating multiple objects at once
    
  1423. =================================
    
  1424. 
    
  1425. Sometimes you want to set a field to a particular value for all the objects in
    
  1426. a :class:`~django.db.models.query.QuerySet`. You can do this with the
    
  1427. :meth:`~django.db.models.query.QuerySet.update` method. For example::
    
  1428. 
    
  1429.     # Update all the headlines with pub_date in 2007.
    
  1430.     Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
    
  1431. 
    
  1432. You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
    
  1433. fields using this method. To update a non-relation field, provide the new value
    
  1434. as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
    
  1435. new value to be the new model instance you want to point to. For example::
    
  1436. 
    
  1437.     >>> b = Blog.objects.get(pk=1)
    
  1438. 
    
  1439.     # Change every Entry so that it belongs to this Blog.
    
  1440.     >>> Entry.objects.update(blog=b)
    
  1441. 
    
  1442. The ``update()`` method is applied instantly and returns the number of rows
    
  1443. matched by the query (which may not be equal to the number of rows updated if
    
  1444. some rows already have the new value). The only restriction on the
    
  1445. :class:`~django.db.models.query.QuerySet` being updated is that it can only
    
  1446. access one database table: the model's main table. You can filter based on
    
  1447. related fields, but you can only update columns in the model's main
    
  1448. table. Example::
    
  1449. 
    
  1450.     >>> b = Blog.objects.get(pk=1)
    
  1451. 
    
  1452.     # Update all the headlines belonging to this Blog.
    
  1453.     >>> Entry.objects.filter(blog=b).update(headline='Everything is the same')
    
  1454. 
    
  1455. Be aware that the ``update()`` method is converted directly to an SQL
    
  1456. statement. It is a bulk operation for direct updates. It doesn't run any
    
  1457. :meth:`~django.db.models.Model.save` methods on your models, or emit the
    
  1458. ``pre_save`` or ``post_save`` signals (which are a consequence of calling
    
  1459. :meth:`~django.db.models.Model.save`), or honor the
    
  1460. :attr:`~django.db.models.DateField.auto_now` field option.
    
  1461. If you want to save every item in a :class:`~django.db.models.query.QuerySet`
    
  1462. and make sure that the :meth:`~django.db.models.Model.save` method is called on
    
  1463. each instance, you don't need any special function to handle that. Loop over
    
  1464. them and call :meth:`~django.db.models.Model.save`::
    
  1465. 
    
  1466.     for item in my_queryset:
    
  1467.         item.save()
    
  1468. 
    
  1469. Calls to update can also use :class:`F expressions <django.db.models.F>` to
    
  1470. update one field based on the value of another field in the model. This is
    
  1471. especially useful for incrementing counters based upon their current value. For
    
  1472. example, to increment the pingback count for every entry in the blog::
    
  1473. 
    
  1474.     >>> Entry.objects.update(number_of_pingbacks=F('number_of_pingbacks') + 1)
    
  1475. 
    
  1476. However, unlike ``F()`` objects in filter and exclude clauses, you can't
    
  1477. introduce joins when you use ``F()`` objects in an update -- you can only
    
  1478. reference fields local to the model being updated. If you attempt to introduce
    
  1479. a join with an ``F()`` object, a ``FieldError`` will be raised::
    
  1480. 
    
  1481.     # This will raise a FieldError
    
  1482.     >>> Entry.objects.update(headline=F('blog__name'))
    
  1483. 
    
  1484. .. _topics-db-queries-related:
    
  1485. 
    
  1486. Related objects
    
  1487. ===============
    
  1488. 
    
  1489. When you define a relationship in a model (i.e., a
    
  1490. :class:`~django.db.models.ForeignKey`,
    
  1491. :class:`~django.db.models.OneToOneField`, or
    
  1492. :class:`~django.db.models.ManyToManyField`), instances of that model will have
    
  1493. a convenient API to access the related object(s).
    
  1494. 
    
  1495. Using the models at the top of this page, for example, an ``Entry`` object ``e``
    
  1496. can get its associated ``Blog`` object by accessing the ``blog`` attribute:
    
  1497. ``e.blog``.
    
  1498. 
    
  1499. (Behind the scenes, this functionality is implemented by Python
    
  1500. :doc:`descriptors <python:howto/descriptor>`. This shouldn't really matter to
    
  1501. you, but we point it out here for the curious.)
    
  1502. 
    
  1503. Django also creates API accessors for the "other" side of the relationship --
    
  1504. the link from the related model to the model that defines the relationship.
    
  1505. For example, a ``Blog`` object ``b`` has access to a list of all related
    
  1506. ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
    
  1507. 
    
  1508. All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
    
  1509. models defined at the top of this page.
    
  1510. 
    
  1511. One-to-many relationships
    
  1512. -------------------------
    
  1513. 
    
  1514. Forward
    
  1515. ~~~~~~~
    
  1516. 
    
  1517. If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
    
  1518. will have access to the related (foreign) object via an attribute of the model.
    
  1519. 
    
  1520. Example::
    
  1521. 
    
  1522.     >>> e = Entry.objects.get(id=2)
    
  1523.     >>> e.blog # Returns the related Blog object.
    
  1524. 
    
  1525. You can get and set via a foreign-key attribute. As you may expect, changes to
    
  1526. the foreign key aren't saved to the database until you call
    
  1527. :meth:`~django.db.models.Model.save`. Example::
    
  1528. 
    
  1529.     >>> e = Entry.objects.get(id=2)
    
  1530.     >>> e.blog = some_blog
    
  1531.     >>> e.save()
    
  1532. 
    
  1533. If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,
    
  1534. it allows ``NULL`` values), you can assign ``None`` to remove the relation.
    
  1535. Example::
    
  1536. 
    
  1537.     >>> e = Entry.objects.get(id=2)
    
  1538.     >>> e.blog = None
    
  1539.     >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
    
  1540. 
    
  1541. Forward access to one-to-many relationships is cached the first time the
    
  1542. related object is accessed. Subsequent accesses to the foreign key on the same
    
  1543. object instance are cached. Example::
    
  1544. 
    
  1545.     >>> e = Entry.objects.get(id=2)
    
  1546.     >>> print(e.blog)  # Hits the database to retrieve the associated Blog.
    
  1547.     >>> print(e.blog)  # Doesn't hit the database; uses cached version.
    
  1548. 
    
  1549. Note that the :meth:`~django.db.models.query.QuerySet.select_related`
    
  1550. :class:`~django.db.models.query.QuerySet` method recursively prepopulates the
    
  1551. cache of all one-to-many relationships ahead of time. Example::
    
  1552. 
    
  1553.     >>> e = Entry.objects.select_related().get(id=2)
    
  1554.     >>> print(e.blog)  # Doesn't hit the database; uses cached version.
    
  1555.     >>> print(e.blog)  # Doesn't hit the database; uses cached version.
    
  1556. 
    
  1557. .. _backwards-related-objects:
    
  1558. 
    
  1559. Following relationships "backward"
    
  1560. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1561. 
    
  1562. If a model has a :class:`~django.db.models.ForeignKey`, instances of the
    
  1563. foreign-key model will have access to a :class:`~django.db.models.Manager` that
    
  1564. returns all instances of the first model. By default, this
    
  1565. :class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the
    
  1566. source model name, lowercased. This :class:`~django.db.models.Manager` returns
    
  1567. ``QuerySets``, which can be filtered and manipulated as described in the
    
  1568. "Retrieving objects" section above.
    
  1569. 
    
  1570. Example::
    
  1571. 
    
  1572.     >>> b = Blog.objects.get(id=1)
    
  1573.     >>> b.entry_set.all() # Returns all Entry objects related to Blog.
    
  1574. 
    
  1575.     # b.entry_set is a Manager that returns QuerySets.
    
  1576.     >>> b.entry_set.filter(headline__contains='Lennon')
    
  1577.     >>> b.entry_set.count()
    
  1578. 
    
  1579. You can override the ``FOO_set`` name by setting the
    
  1580. :attr:`~django.db.models.ForeignKey.related_name` parameter in the
    
  1581. :class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``
    
  1582. model was altered to ``blog = ForeignKey(Blog, on_delete=models.CASCADE,
    
  1583. related_name='entries')``, the above example code would look like this::
    
  1584. 
    
  1585.     >>> b = Blog.objects.get(id=1)
    
  1586.     >>> b.entries.all() # Returns all Entry objects related to Blog.
    
  1587. 
    
  1588.     # b.entries is a Manager that returns QuerySets.
    
  1589.     >>> b.entries.filter(headline__contains='Lennon')
    
  1590.     >>> b.entries.count()
    
  1591. 
    
  1592. .. _using-custom-reverse-manager:
    
  1593. 
    
  1594. Using a custom reverse manager
    
  1595. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1596. 
    
  1597. By default the :class:`~django.db.models.fields.related.RelatedManager` used
    
  1598. for reverse relations is a subclass of the :ref:`default manager <manager-names>`
    
  1599. for that model. If you would like to specify a different manager for a given
    
  1600. query you can use the following syntax::
    
  1601. 
    
  1602.     from django.db import models
    
  1603. 
    
  1604.     class Entry(models.Model):
    
  1605.         #...
    
  1606.         objects = models.Manager()  # Default Manager
    
  1607.         entries = EntryManager()    # Custom Manager
    
  1608. 
    
  1609.     b = Blog.objects.get(id=1)
    
  1610.     b.entry_set(manager='entries').all()
    
  1611. 
    
  1612. If ``EntryManager`` performed default filtering in its ``get_queryset()``
    
  1613. method, that filtering would apply to the ``all()`` call.
    
  1614. 
    
  1615. Specifying a custom reverse manager also enables you to call its custom
    
  1616. methods::
    
  1617. 
    
  1618.     b.entry_set(manager='entries').is_published()
    
  1619. 
    
  1620. Additional methods to handle related objects
    
  1621. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1622. 
    
  1623. In addition to the :class:`~django.db.models.query.QuerySet` methods defined in
    
  1624. "Retrieving objects" above, the :class:`~django.db.models.ForeignKey`
    
  1625. :class:`~django.db.models.Manager` has additional methods used to handle the
    
  1626. set of related objects. A synopsis of each is below, and complete details can
    
  1627. be found in the :doc:`related objects reference </ref/models/relations>`.
    
  1628. 
    
  1629. ``add(obj1, obj2, ...)``
    
  1630.     Adds the specified model objects to the related object set.
    
  1631. 
    
  1632. ``create(**kwargs)``
    
  1633.     Creates a new object, saves it and puts it in the related object set.
    
  1634.     Returns the newly created object.
    
  1635. 
    
  1636. ``remove(obj1, obj2, ...)``
    
  1637.     Removes the specified model objects from the related object set.
    
  1638. 
    
  1639. ``clear()``
    
  1640.     Removes all objects from the related object set.
    
  1641. 
    
  1642. ``set(objs)``
    
  1643.     Replace the set of related objects.
    
  1644. 
    
  1645. To assign the members of a related set, use the ``set()`` method with an
    
  1646. iterable of object instances. For example, if ``e1`` and ``e2`` are ``Entry``
    
  1647. instances::
    
  1648. 
    
  1649.     b = Blog.objects.get(id=1)
    
  1650.     b.entry_set.set([e1, e2])
    
  1651. 
    
  1652. If the ``clear()`` method is available, any preexisting objects will be
    
  1653. removed from the ``entry_set`` before all objects in the iterable (in this
    
  1654. case, a list) are added to the set. If the ``clear()`` method is *not*
    
  1655. available, all objects in the iterable will be added without removing any
    
  1656. existing elements.
    
  1657. 
    
  1658. Each "reverse" operation described in this section has an immediate effect on
    
  1659. the database. Every addition, creation and deletion is immediately and
    
  1660. automatically saved to the database.
    
  1661. 
    
  1662. .. _m2m-reverse-relationships:
    
  1663. 
    
  1664. Many-to-many relationships
    
  1665. --------------------------
    
  1666. 
    
  1667. Both ends of a many-to-many relationship get automatic API access to the other
    
  1668. end. The API works similar to a "backward" one-to-many relationship, above.
    
  1669. 
    
  1670. One difference is in the attribute naming: The model that defines the
    
  1671. :class:`~django.db.models.ManyToManyField` uses the attribute name of that
    
  1672. field itself, whereas the "reverse" model uses the lowercased model name of the
    
  1673. original model, plus ``'_set'`` (just like reverse one-to-many relationships).
    
  1674. 
    
  1675. An example makes this easier to understand::
    
  1676. 
    
  1677.     e = Entry.objects.get(id=3)
    
  1678.     e.authors.all() # Returns all Author objects for this Entry.
    
  1679.     e.authors.count()
    
  1680.     e.authors.filter(name__contains='John')
    
  1681. 
    
  1682.     a = Author.objects.get(id=5)
    
  1683.     a.entry_set.all() # Returns all Entry objects for this Author.
    
  1684. 
    
  1685. Like :class:`~django.db.models.ForeignKey`,
    
  1686. :class:`~django.db.models.ManyToManyField` can specify
    
  1687. :attr:`~django.db.models.ManyToManyField.related_name`. In the above example,
    
  1688. if the :class:`~django.db.models.ManyToManyField` in ``Entry`` had specified
    
  1689. ``related_name='entries'``, then each ``Author`` instance would have an
    
  1690. ``entries`` attribute instead of ``entry_set``.
    
  1691. 
    
  1692. Another difference from one-to-many relationships is that in addition to model
    
  1693. instances,  the ``add()``, ``set()``, and ``remove()`` methods on many-to-many
    
  1694. relationships accept primary key values. For example, if ``e1`` and ``e2`` are
    
  1695. ``Entry`` instances, then these ``set()`` calls work identically::
    
  1696. 
    
  1697.     a = Author.objects.get(id=5)
    
  1698.     a.entry_set.set([e1, e2])
    
  1699.     a.entry_set.set([e1.pk, e2.pk])
    
  1700. 
    
  1701. One-to-one relationships
    
  1702. ------------------------
    
  1703. 
    
  1704. One-to-one relationships are very similar to many-to-one relationships. If you
    
  1705. define a :class:`~django.db.models.OneToOneField` on your model, instances of
    
  1706. that model will have access to the related object via an attribute of the
    
  1707. model.
    
  1708. 
    
  1709. For example::
    
  1710. 
    
  1711.     class EntryDetail(models.Model):
    
  1712.         entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
    
  1713.         details = models.TextField()
    
  1714. 
    
  1715.     ed = EntryDetail.objects.get(id=2)
    
  1716.     ed.entry # Returns the related Entry object.
    
  1717. 
    
  1718. The difference comes in "reverse" queries. The related model in a one-to-one
    
  1719. relationship also has access to a :class:`~django.db.models.Manager` object, but
    
  1720. that :class:`~django.db.models.Manager` represents a single object, rather than
    
  1721. a collection of objects::
    
  1722. 
    
  1723.     e = Entry.objects.get(id=2)
    
  1724.     e.entrydetail # returns the related EntryDetail object
    
  1725. 
    
  1726. If no object has been assigned to this relationship, Django will raise
    
  1727. a ``DoesNotExist`` exception.
    
  1728. 
    
  1729. Instances can be assigned to the reverse relationship in the same way as
    
  1730. you would assign the forward relationship::
    
  1731. 
    
  1732.     e.entrydetail = ed
    
  1733. 
    
  1734. How are the backward relationships possible?
    
  1735. --------------------------------------------
    
  1736. 
    
  1737. Other object-relational mappers require you to define relationships on both
    
  1738. sides. The Django developers believe this is a violation of the DRY (Don't
    
  1739. Repeat Yourself) principle, so Django only requires you to define the
    
  1740. relationship on one end.
    
  1741. 
    
  1742. But how is this possible, given that a model class doesn't know which other
    
  1743. model classes are related to it until those other model classes are loaded?
    
  1744. 
    
  1745. The answer lies in the :data:`app registry <django.apps.apps>`. When Django
    
  1746. starts, it imports each application listed in :setting:`INSTALLED_APPS`, and
    
  1747. then the ``models`` module inside each application. Whenever a new model class
    
  1748. is created, Django adds backward-relationships to any related models. If the
    
  1749. related models haven't been imported yet, Django keeps tracks of the
    
  1750. relationships and adds them when the related models eventually are imported.
    
  1751. 
    
  1752. For this reason, it's particularly important that all the models you're using
    
  1753. be defined in applications listed in :setting:`INSTALLED_APPS`. Otherwise,
    
  1754. backwards relations may not work properly.
    
  1755. 
    
  1756. Queries over related objects
    
  1757. ----------------------------
    
  1758. 
    
  1759. Queries involving related objects follow the same rules as queries involving
    
  1760. normal value fields. When specifying the value for a query to match, you may
    
  1761. use either an object instance itself, or the primary key value for the object.
    
  1762. 
    
  1763. For example, if you have a Blog object ``b`` with ``id=5``, the following
    
  1764. three queries would be identical::
    
  1765. 
    
  1766.     Entry.objects.filter(blog=b) # Query using object instance
    
  1767.     Entry.objects.filter(blog=b.id) # Query using id from instance
    
  1768.     Entry.objects.filter(blog=5) # Query using id directly
    
  1769. 
    
  1770. Falling back to raw SQL
    
  1771. =======================
    
  1772. 
    
  1773. If you find yourself needing to write an SQL query that is too complex for
    
  1774. Django's database-mapper to handle, you can fall back on writing SQL by hand.
    
  1775. Django has a couple of options for writing raw SQL queries; see
    
  1776. :doc:`/topics/db/sql`.
    
  1777. 
    
  1778. Finally, it's important to note that the Django database layer is merely an
    
  1779. interface to your database. You can access your database via other tools,
    
  1780. programming languages or database frameworks; there's nothing Django-specific
    
  1781. about your database.