1. ==========================
    
  2. ``QuerySet`` API reference
    
  3. ==========================
    
  4. 
    
  5. .. currentmodule:: django.db.models.query
    
  6. 
    
  7. This document describes the details of the ``QuerySet`` API. It builds on the
    
  8. material presented in the :doc:`model </topics/db/models>` and :doc:`database
    
  9. query </topics/db/queries>` guides, so you'll probably want to read and
    
  10. understand those documents before reading this one.
    
  11. 
    
  12. Throughout this reference we'll use the :ref:`example blog models
    
  13. <queryset-model-example>` presented in the :doc:`database query guide
    
  14. </topics/db/queries>`.
    
  15. 
    
  16. .. _when-querysets-are-evaluated:
    
  17. 
    
  18. When ``QuerySet``\s are evaluated
    
  19. =================================
    
  20. 
    
  21. Internally, a ``QuerySet`` can be constructed, filtered, sliced, and generally
    
  22. passed around without actually hitting the database. No database activity
    
  23. actually occurs until you do something to evaluate the queryset.
    
  24. 
    
  25. You can evaluate a ``QuerySet`` in the following ways:
    
  26. 
    
  27. * **Iteration.** A ``QuerySet`` is iterable, and it executes its database
    
  28.   query the first time you iterate over it. For example, this will print
    
  29.   the headline of all entries in the database::
    
  30. 
    
  31.       for e in Entry.objects.all():
    
  32.           print(e.headline)
    
  33. 
    
  34.   Note: Don't use this if all you want to do is determine if at least one
    
  35.   result exists. It's more efficient to use :meth:`~QuerySet.exists`.
    
  36. 
    
  37. * **Asynchronous iteration.**. A ``QuerySet`` can also be iterated over using
    
  38.   ``async for``::
    
  39. 
    
  40.       async for e in Entry.objects.all():
    
  41.         results.append(e)
    
  42. 
    
  43.   Both synchronous and asynchronous iterators of QuerySets share the same
    
  44.   underlying cache.
    
  45. 
    
  46.   .. versionchanged:: 4.1
    
  47. 
    
  48.     Support for asynchronous iteration was added.
    
  49. 
    
  50. * **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
    
  51.   be sliced, using Python's array-slicing syntax. Slicing an unevaluated
    
  52.   ``QuerySet`` usually returns another unevaluated ``QuerySet``, but Django
    
  53.   will execute the database query if you use the "step" parameter of slice
    
  54.   syntax, and will return a list. Slicing a ``QuerySet`` that has been
    
  55.   evaluated also returns a list.
    
  56. 
    
  57.   Also note that even though slicing an unevaluated ``QuerySet`` returns
    
  58.   another unevaluated ``QuerySet``, modifying it further (e.g., adding
    
  59.   more filters, or modifying ordering) is not allowed, since that does not
    
  60.   translate well into SQL and it would not have a clear meaning either.
    
  61. 
    
  62. * **Pickling/Caching.** See the following section for details of what
    
  63.   is involved when `pickling QuerySets`_. The important thing for the
    
  64.   purposes of this section is that the results are read from the database.
    
  65. 
    
  66. * **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
    
  67.   This is for convenience in the Python interactive interpreter, so you can
    
  68.   immediately see your results when using the API interactively.
    
  69. 
    
  70. * **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
    
  71.   This, as you might expect, returns the length of the result list.
    
  72. 
    
  73.   Note: If you only need to determine the number of records in the set (and
    
  74.   don't need the actual objects), it's much more efficient to handle a count
    
  75.   at the database level using SQL's ``SELECT COUNT(*)``. Django provides a
    
  76.   :meth:`~QuerySet.count` method for precisely this reason.
    
  77. 
    
  78. * **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
    
  79.   it. For example::
    
  80. 
    
  81.       entry_list = list(Entry.objects.all())
    
  82. 
    
  83. * **bool().** Testing a ``QuerySet`` in a boolean context, such as using
    
  84.   ``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query
    
  85.   to be executed. If there is at least one result, the ``QuerySet`` is
    
  86.   ``True``, otherwise ``False``. For example::
    
  87. 
    
  88.       if Entry.objects.filter(headline="Test"):
    
  89.          print("There is at least one Entry with the headline Test")
    
  90. 
    
  91.   Note: If you only want to determine if at least one result exists (and don't
    
  92.   need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`.
    
  93. 
    
  94. .. _pickling QuerySets:
    
  95. 
    
  96. Pickling ``QuerySet``\s
    
  97. -----------------------
    
  98. 
    
  99. If you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded
    
  100. into memory prior to pickling. Pickling is usually used as a precursor to
    
  101. caching and when the cached queryset is reloaded, you want the results to
    
  102. already be present and ready for use (reading from the database can take some
    
  103. time, defeating the purpose of caching). This means that when you unpickle a
    
  104. ``QuerySet``, it contains the results at the moment it was pickled, rather
    
  105. than the results that are currently in the database.
    
  106. 
    
  107. If you only want to pickle the necessary information to recreate the
    
  108. ``QuerySet`` from the database at a later time, pickle the ``query`` attribute
    
  109. of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
    
  110. any results loaded) using some code like this::
    
  111. 
    
  112.     >>> import pickle
    
  113.     >>> query = pickle.loads(s)     # Assuming 's' is the pickled string.
    
  114.     >>> qs = MyModel.objects.all()
    
  115.     >>> qs.query = query            # Restore the original 'query'.
    
  116. 
    
  117. The ``query`` attribute is an opaque object. It represents the internals of
    
  118. the query construction and is not part of the public API. However, it is safe
    
  119. (and fully supported) to pickle and unpickle the attribute's contents as
    
  120. described here.
    
  121. 
    
  122. .. admonition:: Restrictions on ``QuerySet.values_list()``
    
  123. 
    
  124.     If you recreate :meth:`QuerySet.values_list` using the pickled ``query``
    
  125.     attribute, it will be converted to :meth:`QuerySet.values`::
    
  126. 
    
  127.         >>> import pickle
    
  128.         >>> qs = Blog.objects.values_list('id', 'name')
    
  129.         >>> qs
    
  130.         <QuerySet [(1, 'Beatles Blog')]>
    
  131.         >>> reloaded_qs = Blog.objects.all()
    
  132.         >>> reloaded_qs.query = pickle.loads(pickle.dumps(qs.query))
    
  133.         >>> reloaded_qs
    
  134.         <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
    
  135. 
    
  136. .. admonition:: You can't share pickles between versions
    
  137. 
    
  138.     Pickles of ``QuerySets`` are only valid for the version of Django that
    
  139.     was used to generate them. If you generate a pickle using Django
    
  140.     version N, there is no guarantee that pickle will be readable with
    
  141.     Django version N+1. Pickles should not be used as part of a long-term
    
  142.     archival strategy.
    
  143. 
    
  144.     Since pickle compatibility errors can be difficult to diagnose, such as
    
  145.     silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
    
  146.     unpickle a queryset in a Django version that is different than the one in
    
  147.     which it was pickled.
    
  148. 
    
  149. .. _queryset-api:
    
  150. 
    
  151. ``QuerySet`` API
    
  152. ================
    
  153. 
    
  154. Here's the formal declaration of a ``QuerySet``:
    
  155. 
    
  156. .. class:: QuerySet(model=None, query=None, using=None, hints=None)
    
  157. 
    
  158.     Usually when you'll interact with a ``QuerySet`` you'll use it by
    
  159.     :ref:`chaining filters <chaining-filters>`. To make this work, most
    
  160.     ``QuerySet`` methods return new querysets. These methods are covered in
    
  161.     detail later in this section.
    
  162. 
    
  163.     The ``QuerySet`` class has the following public attributes you can use for
    
  164.     introspection:
    
  165. 
    
  166.     .. attribute:: ordered
    
  167. 
    
  168.         ``True`` if the ``QuerySet`` is ordered — i.e. has an
    
  169.         :meth:`order_by()` clause or a default ordering on the model.
    
  170.         ``False`` otherwise.
    
  171. 
    
  172.     .. attribute:: db
    
  173. 
    
  174.         The database that will be used if this query is executed now.
    
  175. 
    
  176.     .. note::
    
  177. 
    
  178.         The ``query`` parameter to :class:`QuerySet` exists so that specialized
    
  179.         query subclasses can reconstruct internal query state. The value of the
    
  180.         parameter is an opaque representation of that query state and is not
    
  181.         part of a public API.
    
  182. 
    
  183. .. currentmodule:: django.db.models.query.QuerySet
    
  184. 
    
  185. Methods that return new ``QuerySet``\s
    
  186. --------------------------------------
    
  187. 
    
  188. Django provides a range of ``QuerySet`` refinement methods that modify either
    
  189. the types of results returned by the ``QuerySet`` or the way its SQL query is
    
  190. executed.
    
  191. 
    
  192. .. note::
    
  193. 
    
  194.     These methods do not run database queries, therefore they are **safe to**
    
  195.     **run in asynchronous code**, and do not have separate asynchronous
    
  196.     versions.
    
  197. 
    
  198. ``filter()``
    
  199. ~~~~~~~~~~~~
    
  200. 
    
  201. .. method:: filter(*args, **kwargs)
    
  202. 
    
  203. Returns a new ``QuerySet`` containing objects that match the given lookup
    
  204. parameters.
    
  205. 
    
  206. The lookup parameters (``**kwargs``) should be in the format described in
    
  207. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
    
  208. underlying SQL statement.
    
  209. 
    
  210. If you need to execute more complex queries (for example, queries with ``OR`` statements),
    
  211. you can use :class:`Q objects <django.db.models.Q>` (``*args``).
    
  212. 
    
  213. ``exclude()``
    
  214. ~~~~~~~~~~~~~
    
  215. 
    
  216. .. method:: exclude(*args, **kwargs)
    
  217. 
    
  218. Returns a new ``QuerySet`` containing objects that do *not* match the given
    
  219. lookup parameters.
    
  220. 
    
  221. The lookup parameters (``**kwargs``) should be in the format described in
    
  222. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
    
  223. underlying SQL statement, and the whole thing is enclosed in a ``NOT()``.
    
  224. 
    
  225. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
    
  226. AND whose ``headline`` is "Hello"::
    
  227. 
    
  228.     Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
    
  229. 
    
  230. In SQL terms, that evaluates to:
    
  231. 
    
  232. .. code-block:: sql
    
  233. 
    
  234.     SELECT ...
    
  235.     WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
    
  236. 
    
  237. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
    
  238. OR whose headline is "Hello"::
    
  239. 
    
  240.     Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
    
  241. 
    
  242. In SQL terms, that evaluates to:
    
  243. 
    
  244. .. code-block:: sql
    
  245. 
    
  246.     SELECT ...
    
  247.     WHERE NOT pub_date > '2005-1-3'
    
  248.     AND NOT headline = 'Hello'
    
  249. 
    
  250. Note the second example is more restrictive.
    
  251. 
    
  252. If you need to execute more complex queries (for example, queries with ``OR`` statements),
    
  253. you can use :class:`Q objects <django.db.models.Q>` (``*args``).
    
  254. 
    
  255. ``annotate()``
    
  256. ~~~~~~~~~~~~~~
    
  257. 
    
  258. .. method:: annotate(*args, **kwargs)
    
  259. 
    
  260. Annotates each object in the ``QuerySet`` with the provided list of :doc:`query
    
  261. expressions </ref/models/expressions>`. An expression may be a simple value, a
    
  262. reference to a field on the model (or any related models), or an aggregate
    
  263. expression (averages, sums, etc.) that has been computed over the objects that
    
  264. are related to the objects in the ``QuerySet``.
    
  265. 
    
  266. Each argument to ``annotate()`` is an annotation that will be added
    
  267. to each object in the ``QuerySet`` that is returned.
    
  268. 
    
  269. The aggregation functions that are provided by Django are described
    
  270. in `Aggregation Functions`_ below.
    
  271. 
    
  272. Annotations specified using keyword arguments will use the keyword as
    
  273. the alias for the annotation. Anonymous arguments will have an alias
    
  274. generated for them based upon the name of the aggregate function and
    
  275. the model field that is being aggregated. Only aggregate expressions
    
  276. that reference a single field can be anonymous arguments. Everything
    
  277. else must be a keyword argument.
    
  278. 
    
  279. For example, if you were manipulating a list of blogs, you may want
    
  280. to determine how many entries have been made in each blog::
    
  281. 
    
  282.     >>> from django.db.models import Count
    
  283.     >>> q = Blog.objects.annotate(Count('entry'))
    
  284.     # The name of the first blog
    
  285.     >>> q[0].name
    
  286.     'Blogasaurus'
    
  287.     # The number of entries on the first blog
    
  288.     >>> q[0].entry__count
    
  289.     42
    
  290. 
    
  291. The ``Blog`` model doesn't define an ``entry__count`` attribute by itself,
    
  292. but by using a keyword argument to specify the aggregate function, you can
    
  293. control the name of the annotation::
    
  294. 
    
  295.     >>> q = Blog.objects.annotate(number_of_entries=Count('entry'))
    
  296.     # The number of entries on the first blog, using the name provided
    
  297.     >>> q[0].number_of_entries
    
  298.     42
    
  299. 
    
  300. For an in-depth discussion of aggregation, see :doc:`the topic guide on
    
  301. Aggregation </topics/db/aggregation>`.
    
  302. 
    
  303. ``alias()``
    
  304. ~~~~~~~~~~~
    
  305. 
    
  306. .. method:: alias(*args, **kwargs)
    
  307. 
    
  308. Same as :meth:`annotate`, but instead of annotating objects in the
    
  309. ``QuerySet``, saves the expression for later reuse with other ``QuerySet``
    
  310. methods. This is useful when the result of the expression itself is not needed
    
  311. but it is used for filtering, ordering, or as a part of a complex expression.
    
  312. Not selecting the unused value removes redundant work from the database which
    
  313. should result in better performance.
    
  314. 
    
  315. For example, if you want to find blogs with more than 5 entries, but are not
    
  316. interested in the exact number of entries, you could do this::
    
  317. 
    
  318.     >>> from django.db.models import Count
    
  319.     >>> blogs = Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)
    
  320. 
    
  321. ``alias()`` can be used in conjunction with :meth:`annotate`, :meth:`exclude`,
    
  322. :meth:`filter`, :meth:`order_by`, and :meth:`update`. To use aliased expression
    
  323. with other methods (e.g. :meth:`aggregate`), you must promote it to an
    
  324. annotation::
    
  325. 
    
  326.     Blog.objects.alias(entries=Count('entry')).annotate(
    
  327.         entries=F('entries'),
    
  328.     ).aggregate(Sum('entries'))
    
  329. 
    
  330. :meth:`filter` and :meth:`order_by` can take expressions directly, but
    
  331. expression construction and usage often does not happen in the same place (for
    
  332. example, ``QuerySet`` method creates expressions, for later use in views).
    
  333. ``alias()`` allows building complex expressions incrementally, possibly
    
  334. spanning multiple methods and modules, refer to the expression parts by their
    
  335. aliases and only use :meth:`annotate` for the final result.
    
  336. 
    
  337. ``order_by()``
    
  338. ~~~~~~~~~~~~~~
    
  339. 
    
  340. .. method:: order_by(*fields)
    
  341. 
    
  342. By default, results returned by a ``QuerySet`` are ordered by the ordering
    
  343. tuple given by the ``ordering`` option in the model's ``Meta``. You can
    
  344. override this on a per-``QuerySet`` basis by using the ``order_by`` method.
    
  345. 
    
  346. Example::
    
  347. 
    
  348.     Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
    
  349. 
    
  350. The result above will be ordered by ``pub_date`` descending, then by
    
  351. ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
    
  352. *descending* order. Ascending order is implied. To order randomly, use ``"?"``,
    
  353. like so::
    
  354. 
    
  355.     Entry.objects.order_by('?')
    
  356. 
    
  357. Note: ``order_by('?')`` queries may be expensive and slow, depending on the
    
  358. database backend you're using.
    
  359. 
    
  360. To order by a field in a different model, use the same syntax as when you are
    
  361. querying across model relations. That is, the name of the field, followed by a
    
  362. double underscore (``__``), followed by the name of the field in the new model,
    
  363. and so on for as many models as you want to join. For example::
    
  364. 
    
  365.     Entry.objects.order_by('blog__name', 'headline')
    
  366. 
    
  367. If you try to order by a field that is a relation to another model, Django will
    
  368. use the default ordering on the related model, or order by the related model's
    
  369. primary key if there is no :attr:`Meta.ordering
    
  370. <django.db.models.Options.ordering>` specified. For example, since the ``Blog``
    
  371. model has no default ordering specified::
    
  372. 
    
  373.     Entry.objects.order_by('blog')
    
  374. 
    
  375. ...is identical to::
    
  376. 
    
  377.     Entry.objects.order_by('blog__id')
    
  378. 
    
  379. If ``Blog`` had ``ordering = ['name']``, then the first queryset would be
    
  380. identical to::
    
  381. 
    
  382.     Entry.objects.order_by('blog__name')
    
  383. 
    
  384. You can also order by :doc:`query expressions </ref/models/expressions>` by
    
  385. calling :meth:`~.Expression.asc` or :meth:`~.Expression.desc` on the
    
  386. expression::
    
  387. 
    
  388.     Entry.objects.order_by(Coalesce('summary', 'headline').desc())
    
  389. 
    
  390. :meth:`~.Expression.asc` and :meth:`~.Expression.desc` have arguments
    
  391. (``nulls_first`` and ``nulls_last``) that control how null values are sorted.
    
  392. 
    
  393. Be cautious when ordering by fields in related models if you are also using
    
  394. :meth:`distinct()`. See the note in :meth:`distinct` for an explanation of how
    
  395. related model ordering can change the expected results.
    
  396. 
    
  397. .. note::
    
  398.     It is permissible to specify a multi-valued field to order the results by
    
  399.     (for example, a :class:`~django.db.models.ManyToManyField` field, or the
    
  400.     reverse relation of a :class:`~django.db.models.ForeignKey` field).
    
  401. 
    
  402.     Consider this case::
    
  403. 
    
  404.          class Event(Model):
    
  405.             parent = models.ForeignKey(
    
  406.                 'self',
    
  407.                 on_delete=models.CASCADE,
    
  408.                 related_name='children',
    
  409.             )
    
  410.             date = models.DateField()
    
  411. 
    
  412.          Event.objects.order_by('children__date')
    
  413. 
    
  414.     Here, there could potentially be multiple ordering data for each ``Event``;
    
  415.     each ``Event`` with multiple ``children`` will be returned multiple times
    
  416.     into the new ``QuerySet`` that ``order_by()`` creates. In other words,
    
  417.     using ``order_by()`` on the ``QuerySet`` could return more items than you
    
  418.     were working on to begin with - which is probably neither expected nor
    
  419.     useful.
    
  420. 
    
  421.     Thus, take care when using multi-valued field to order the results. **If**
    
  422.     you can be sure that there will only be one ordering piece of data for each
    
  423.     of the items you're ordering, this approach should not present problems. If
    
  424.     not, make sure the results are what you expect.
    
  425. 
    
  426. There's no way to specify whether ordering should be case sensitive. With
    
  427. respect to case-sensitivity, Django will order results however your database
    
  428. backend normally orders them.
    
  429. 
    
  430. You can order by a field converted to lowercase with
    
  431. :class:`~django.db.models.functions.Lower` which will achieve case-consistent
    
  432. ordering::
    
  433. 
    
  434.     Entry.objects.order_by(Lower('headline').desc())
    
  435. 
    
  436. If you don't want any ordering to be applied to a query, not even the default
    
  437. ordering, call :meth:`order_by()` with no parameters.
    
  438. 
    
  439. You can tell if a query is ordered or not by checking the
    
  440. :attr:`.QuerySet.ordered` attribute, which will be ``True`` if the
    
  441. ``QuerySet`` has been ordered in any way.
    
  442. 
    
  443. Each ``order_by()`` call will clear any previous ordering. For example, this
    
  444. query will be ordered by ``pub_date`` and not ``headline``::
    
  445. 
    
  446.     Entry.objects.order_by('headline').order_by('pub_date')
    
  447. 
    
  448. .. warning::
    
  449. 
    
  450.     Ordering is not a free operation. Each field you add to the ordering
    
  451.     incurs a cost to your database. Each foreign key you add will
    
  452.     implicitly include all of its default orderings as well.
    
  453. 
    
  454.     If a query doesn't have an ordering specified, results are returned from
    
  455.     the database in an unspecified order. A particular ordering is guaranteed
    
  456.     only when ordering by a set of fields that uniquely identify each object in
    
  457.     the results. For example, if a ``name`` field isn't unique, ordering by it
    
  458.     won't guarantee objects with the same name always appear in the same order.
    
  459. 
    
  460. ``reverse()``
    
  461. ~~~~~~~~~~~~~
    
  462. 
    
  463. .. method:: reverse()
    
  464. 
    
  465. Use the ``reverse()`` method to reverse the order in which a queryset's
    
  466. elements are returned. Calling ``reverse()`` a second time restores the
    
  467. ordering back to the normal direction.
    
  468. 
    
  469. To retrieve the "last" five items in a queryset, you could do this::
    
  470. 
    
  471.     my_queryset.reverse()[:5]
    
  472. 
    
  473. Note that this is not quite the same as slicing from the end of a sequence in
    
  474. Python. The above example will return the last item first, then the
    
  475. penultimate item and so on. If we had a Python sequence and looked at
    
  476. ``seq[-5:]``, we would see the fifth-last item first. Django doesn't support
    
  477. that mode of access (slicing from the end), because it's not possible to do it
    
  478. efficiently in SQL.
    
  479. 
    
  480. Also, note that ``reverse()`` should generally only be called on a ``QuerySet``
    
  481. which has a defined ordering (e.g., when querying against a model which defines
    
  482. a default ordering, or when using :meth:`order_by()`). If no such ordering is
    
  483. defined for a given ``QuerySet``, calling ``reverse()`` on it has no real
    
  484. effect (the ordering was undefined prior to calling ``reverse()``, and will
    
  485. remain undefined afterward).
    
  486. 
    
  487. ``distinct()``
    
  488. ~~~~~~~~~~~~~~
    
  489. 
    
  490. .. method:: distinct(*fields)
    
  491. 
    
  492. Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
    
  493. eliminates duplicate rows from the query results.
    
  494. 
    
  495. By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
    
  496. is rarely a problem, because simple queries such as ``Blog.objects.all()``
    
  497. don't introduce the possibility of duplicate result rows. However, if your
    
  498. query spans multiple tables, it's possible to get duplicate results when a
    
  499. ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
    
  500. 
    
  501. .. note::
    
  502.     Any fields used in an :meth:`order_by` call are included in the SQL
    
  503.     ``SELECT`` columns. This can sometimes lead to unexpected results when used
    
  504.     in conjunction with ``distinct()``. If you order by fields from a related
    
  505.     model, those fields will be added to the selected columns and they may make
    
  506.     otherwise duplicate rows appear to be distinct. Since the extra columns
    
  507.     don't appear in the returned results (they are only there to support
    
  508.     ordering), it sometimes looks like non-distinct results are being returned.
    
  509. 
    
  510.     Similarly, if you use a :meth:`values()` query to restrict the columns
    
  511.     selected, the columns used in any :meth:`order_by()` (or default model
    
  512.     ordering) will still be involved and may affect uniqueness of the results.
    
  513. 
    
  514.     The moral here is that if you are using ``distinct()`` be careful about
    
  515.     ordering by related models. Similarly, when using ``distinct()`` and
    
  516.     :meth:`values()` together, be careful when ordering by fields not in the
    
  517.     :meth:`values()` call.
    
  518. 
    
  519. On PostgreSQL only, you can pass positional arguments (``*fields``) in order to
    
  520. specify the names of fields to which the ``DISTINCT`` should apply. This
    
  521. translates to a ``SELECT DISTINCT ON`` SQL query. Here's the difference. For a
    
  522. normal ``distinct()`` call, the database compares *each* field in each row when
    
  523. determining which rows are distinct. For a ``distinct()`` call with specified
    
  524. field names, the database will only compare the specified field names.
    
  525. 
    
  526. .. note::
    
  527.     When you specify field names, you *must* provide an ``order_by()`` in the
    
  528.     ``QuerySet``, and the fields in ``order_by()`` must start with the fields in
    
  529.     ``distinct()``, in the same order.
    
  530. 
    
  531.     For example, ``SELECT DISTINCT ON (a)`` gives you the first row for each
    
  532.     value in column ``a``. If you don't specify an order, you'll get some
    
  533.     arbitrary row.
    
  534. 
    
  535. Examples (those after the first will only work on PostgreSQL)::
    
  536. 
    
  537.     >>> Author.objects.distinct()
    
  538.     [...]
    
  539. 
    
  540.     >>> Entry.objects.order_by('pub_date').distinct('pub_date')
    
  541.     [...]
    
  542. 
    
  543.     >>> Entry.objects.order_by('blog').distinct('blog')
    
  544.     [...]
    
  545. 
    
  546.     >>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
    
  547.     [...]
    
  548. 
    
  549.     >>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
    
  550.     [...]
    
  551. 
    
  552.     >>> Entry.objects.order_by('author', 'pub_date').distinct('author')
    
  553.     [...]
    
  554. 
    
  555. .. note::
    
  556.     Keep in mind that :meth:`order_by` uses any default related model ordering
    
  557.     that has been defined. You might have to explicitly order by the relation
    
  558.     ``_id`` or referenced field to make sure the ``DISTINCT ON`` expressions
    
  559.     match those at the beginning of the ``ORDER BY`` clause. For example, if
    
  560.     the ``Blog`` model defined an :attr:`~django.db.models.Options.ordering` by
    
  561.     ``name``::
    
  562. 
    
  563.         Entry.objects.order_by('blog').distinct('blog')
    
  564. 
    
  565.     ...wouldn't work because the query would be ordered by ``blog__name`` thus
    
  566.     mismatching the ``DISTINCT ON`` expression. You'd have to explicitly order
    
  567.     by the relation ``_id`` field (``blog_id`` in this case) or the referenced
    
  568.     one (``blog__pk``) to make sure both expressions match.
    
  569. 
    
  570. ``values()``
    
  571. ~~~~~~~~~~~~
    
  572. 
    
  573. .. method:: values(*fields, **expressions)
    
  574. 
    
  575. Returns a ``QuerySet`` that returns dictionaries, rather than model instances,
    
  576. when used as an iterable.
    
  577. 
    
  578. Each of those dictionaries represents an object, with the keys corresponding to
    
  579. the attribute names of model objects.
    
  580. 
    
  581. This example compares the dictionaries of ``values()`` with the normal model
    
  582. objects::
    
  583. 
    
  584.     # This list contains a Blog object.
    
  585.     >>> Blog.objects.filter(name__startswith='Beatles')
    
  586.     <QuerySet [<Blog: Beatles Blog>]>
    
  587. 
    
  588.     # This list contains a dictionary.
    
  589.     >>> Blog.objects.filter(name__startswith='Beatles').values()
    
  590.     <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
    
  591. 
    
  592. The ``values()`` method takes optional positional arguments, ``*fields``, which
    
  593. specify field names to which the ``SELECT`` should be limited. If you specify
    
  594. the fields, each dictionary will contain only the field keys/values for the
    
  595. fields you specify. If you don't specify the fields, each dictionary will
    
  596. contain a key and value for every field in the database table.
    
  597. 
    
  598. Example::
    
  599. 
    
  600.     >>> Blog.objects.values()
    
  601.     <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
    
  602.     >>> Blog.objects.values('id', 'name')
    
  603.     <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
    
  604. 
    
  605. The ``values()`` method also takes optional keyword arguments,
    
  606. ``**expressions``, which are passed through to :meth:`annotate`::
    
  607. 
    
  608.     >>> from django.db.models.functions import Lower
    
  609.     >>> Blog.objects.values(lower_name=Lower('name'))
    
  610.     <QuerySet [{'lower_name': 'beatles blog'}]>
    
  611. 
    
  612. You can use built-in and :doc:`custom lookups </howto/custom-lookups>` in
    
  613. ordering. For example::
    
  614. 
    
  615.     >>> from django.db.models import CharField
    
  616.     >>> from django.db.models.functions import Lower
    
  617.     >>> CharField.register_lookup(Lower)
    
  618.     >>> Blog.objects.values('name__lower')
    
  619.     <QuerySet [{'name__lower': 'beatles blog'}]>
    
  620. 
    
  621. An aggregate within a ``values()`` clause is applied before other arguments
    
  622. within the same ``values()`` clause. If you need to group by another value,
    
  623. add it to an earlier ``values()`` clause instead. For example::
    
  624. 
    
  625.     >>> from django.db.models import Count
    
  626.     >>> Blog.objects.values('entry__authors', entries=Count('entry'))
    
  627.     <QuerySet [{'entry__authors': 1, 'entries': 20}, {'entry__authors': 1, 'entries': 13}]>
    
  628.     >>> Blog.objects.values('entry__authors').annotate(entries=Count('entry'))
    
  629.     <QuerySet [{'entry__authors': 1, 'entries': 33}]>
    
  630. 
    
  631. A few subtleties that are worth mentioning:
    
  632. 
    
  633. * If you have a field called ``foo`` that is a
    
  634.   :class:`~django.db.models.ForeignKey`, the default ``values()`` call
    
  635.   will return a dictionary key called ``foo_id``, since this is the name
    
  636.   of the hidden model attribute that stores the actual value (the ``foo``
    
  637.   attribute refers to the related model). When you are calling
    
  638.   ``values()`` and passing in field names, you can pass in either ``foo``
    
  639.   or ``foo_id`` and you will get back the same thing (the dictionary key
    
  640.   will match the field name you passed in).
    
  641. 
    
  642.   For example::
    
  643. 
    
  644.     >>> Entry.objects.values()
    
  645.     <QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>
    
  646. 
    
  647.     >>> Entry.objects.values('blog')
    
  648.     <QuerySet [{'blog': 1}, ...]>
    
  649. 
    
  650.     >>> Entry.objects.values('blog_id')
    
  651.     <QuerySet [{'blog_id': 1}, ...]>
    
  652. 
    
  653. * When using ``values()`` together with :meth:`distinct()`, be aware that
    
  654.   ordering can affect the results. See the note in :meth:`distinct` for
    
  655.   details.
    
  656. 
    
  657. * If you use a ``values()`` clause after an :meth:`extra()` call,
    
  658.   any fields defined by a ``select`` argument in the :meth:`extra()` must
    
  659.   be explicitly included in the ``values()`` call. Any :meth:`extra()` call
    
  660.   made after a ``values()`` call will have its extra selected fields
    
  661.   ignored.
    
  662. 
    
  663. * Calling :meth:`only()` and :meth:`defer()` after ``values()`` doesn't make
    
  664.   sense, so doing so will raise a ``TypeError``.
    
  665. 
    
  666. * Combining transforms and aggregates requires the use of two :meth:`annotate`
    
  667.   calls, either explicitly or as keyword arguments to :meth:`values`. As above,
    
  668.   if the transform has been registered on the relevant field type the first
    
  669.   :meth:`annotate` can be omitted, thus the following examples are equivalent::
    
  670. 
    
  671.     >>> from django.db.models import CharField, Count
    
  672.     >>> from django.db.models.functions import Lower
    
  673.     >>> CharField.register_lookup(Lower)
    
  674.     >>> Blog.objects.values('entry__authors__name__lower').annotate(entries=Count('entry'))
    
  675.     <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
    
  676.     >>> Blog.objects.values(
    
  677.     ...     entry__authors__name__lower=Lower('entry__authors__name')
    
  678.     ... ).annotate(entries=Count('entry'))
    
  679.     <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
    
  680.     >>> Blog.objects.annotate(
    
  681.     ...     entry__authors__name__lower=Lower('entry__authors__name')
    
  682.     ... ).values('entry__authors__name__lower').annotate(entries=Count('entry'))
    
  683.     <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
    
  684. 
    
  685. It is useful when you know you're only going to need values from a small number
    
  686. of the available fields and you won't need the functionality of a model
    
  687. instance object. It's more efficient to select only the fields you need to use.
    
  688. 
    
  689. Finally, note that you can call ``filter()``, ``order_by()``, etc. after the
    
  690. ``values()`` call, that means that these two calls are identical::
    
  691. 
    
  692.     Blog.objects.values().order_by('id')
    
  693.     Blog.objects.order_by('id').values()
    
  694. 
    
  695. The people who made Django prefer to put all the SQL-affecting methods first,
    
  696. followed (optionally) by any output-affecting methods (such as ``values()``),
    
  697. but it doesn't really matter. This is your chance to really flaunt your
    
  698. individualism.
    
  699. 
    
  700. You can also refer to fields on related models with reverse relations through
    
  701. ``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes::
    
  702. 
    
  703.     >>> Blog.objects.values('name', 'entry__headline')
    
  704.     <QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'},
    
  705.          {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]>
    
  706. 
    
  707. .. warning::
    
  708. 
    
  709.    Because :class:`~django.db.models.ManyToManyField` attributes and reverse
    
  710.    relations can have multiple related rows, including these can have a
    
  711.    multiplier effect on the size of your result set. This will be especially
    
  712.    pronounced if you include multiple such fields in your ``values()`` query,
    
  713.    in which case all possible combinations will be returned.
    
  714. 
    
  715. .. admonition:: Special values for ``JSONField`` on SQLite
    
  716. 
    
  717.     Due to the way the ``JSON_EXTRACT`` and ``JSON_TYPE`` SQL functions are
    
  718.     implemented on SQLite, and lack of the ``BOOLEAN`` data type,
    
  719.     ``values()`` will return ``True``, ``False``, and ``None`` instead of
    
  720.     ``"true"``, ``"false"``, and ``"null"`` strings for
    
  721.     :class:`~django.db.models.JSONField` key transforms.
    
  722. 
    
  723. ``values_list()``
    
  724. ~~~~~~~~~~~~~~~~~
    
  725. 
    
  726. .. method:: values_list(*fields, flat=False, named=False)
    
  727. 
    
  728. This is similar to ``values()`` except that instead of returning dictionaries,
    
  729. it returns tuples when iterated over. Each tuple contains the value from the
    
  730. respective field or expression passed into the ``values_list()`` call — so the
    
  731. first item is the first field, etc. For example::
    
  732. 
    
  733.     >>> Entry.objects.values_list('id', 'headline')
    
  734.     <QuerySet [(1, 'First entry'), ...]>
    
  735.     >>> from django.db.models.functions import Lower
    
  736.     >>> Entry.objects.values_list('id', Lower('headline'))
    
  737.     <QuerySet [(1, 'first entry'), ...]>
    
  738. 
    
  739. If you only pass in a single field, you can also pass in the ``flat``
    
  740. parameter. If ``True``, this will mean the returned results are single values,
    
  741. rather than one-tuples. An example should make the difference clearer::
    
  742. 
    
  743.     >>> Entry.objects.values_list('id').order_by('id')
    
  744.     <QuerySet[(1,), (2,), (3,), ...]>
    
  745. 
    
  746.     >>> Entry.objects.values_list('id', flat=True).order_by('id')
    
  747.     <QuerySet [1, 2, 3, ...]>
    
  748. 
    
  749. It is an error to pass in ``flat`` when there is more than one field.
    
  750. 
    
  751. You can pass ``named=True`` to get results as a
    
  752. :func:`~python:collections.namedtuple`::
    
  753. 
    
  754.     >>> Entry.objects.values_list('id', 'headline', named=True)
    
  755.     <QuerySet [Row(id=1, headline='First entry'), ...]>
    
  756. 
    
  757. Using a named tuple may make use of the results more readable, at the expense
    
  758. of a small performance penalty for transforming the results into a named tuple.
    
  759. 
    
  760. If you don't pass any values to ``values_list()``, it will return all the
    
  761. fields in the model, in the order they were declared.
    
  762. 
    
  763. A common need is to get a specific field value of a certain model instance. To
    
  764. achieve that, use ``values_list()`` followed by a ``get()`` call::
    
  765. 
    
  766.     >>> Entry.objects.values_list('headline', flat=True).get(pk=1)
    
  767.     'First entry'
    
  768. 
    
  769. ``values()`` and ``values_list()`` are both intended as optimizations for a
    
  770. specific use case: retrieving a subset of data without the overhead of creating
    
  771. a model instance. This metaphor falls apart when dealing with many-to-many and
    
  772. other multivalued relations (such as the one-to-many relation of a reverse
    
  773. foreign key) because the "one row, one object" assumption doesn't hold.
    
  774. 
    
  775. For example, notice the behavior when querying across a
    
  776. :class:`~django.db.models.ManyToManyField`::
    
  777. 
    
  778.     >>> Author.objects.values_list('name', 'entry__headline')
    
  779.     <QuerySet [('Noam Chomsky', 'Impressions of Gaza'),
    
  780.      ('George Orwell', 'Why Socialists Do Not Believe in Fun'),
    
  781.      ('George Orwell', 'In Defence of English Cooking'),
    
  782.      ('Don Quixote', None)]>
    
  783. 
    
  784. Authors with multiple entries appear multiple times and authors without any
    
  785. entries have ``None`` for the entry headline.
    
  786. 
    
  787. Similarly, when querying a reverse foreign key, ``None`` appears for entries
    
  788. not having any author::
    
  789. 
    
  790.     >>> Entry.objects.values_list('authors')
    
  791.     <QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>
    
  792. 
    
  793. .. admonition:: Special values for ``JSONField`` on SQLite
    
  794. 
    
  795.     Due to the way the ``JSON_EXTRACT`` and ``JSON_TYPE`` SQL functions are
    
  796.     implemented on SQLite, and lack of the ``BOOLEAN`` data type,
    
  797.     ``values_list()`` will return ``True``, ``False``, and ``None`` instead of
    
  798.     ``"true"``, ``"false"``, and ``"null"`` strings for
    
  799.     :class:`~django.db.models.JSONField` key transforms.
    
  800. 
    
  801. ``dates()``
    
  802. ~~~~~~~~~~~
    
  803. 
    
  804. .. method:: dates(field, kind, order='ASC')
    
  805. 
    
  806. Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.date`
    
  807. objects representing all available dates of a particular kind within the
    
  808. contents of the ``QuerySet``.
    
  809. 
    
  810. ``field`` should be the name of a ``DateField`` of your model.
    
  811. ``kind`` should be either ``"year"``, ``"month"``, ``"week"``, or ``"day"``.
    
  812. Each :class:`datetime.date` object in the result list is "truncated" to the
    
  813. given ``type``.
    
  814. 
    
  815. * ``"year"`` returns a list of all distinct year values for the field.
    
  816. * ``"month"`` returns a list of all distinct year/month values for the
    
  817.   field.
    
  818. * ``"week"`` returns a list of all distinct year/week values for the field. All
    
  819.   dates will be a Monday.
    
  820. * ``"day"`` returns a list of all distinct year/month/day values for the
    
  821.   field.
    
  822. 
    
  823. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
    
  824. ``'DESC'``. This specifies how to order the results.
    
  825. 
    
  826. Examples::
    
  827. 
    
  828.     >>> Entry.objects.dates('pub_date', 'year')
    
  829.     [datetime.date(2005, 1, 1)]
    
  830.     >>> Entry.objects.dates('pub_date', 'month')
    
  831.     [datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
    
  832.     >>> Entry.objects.dates('pub_date', 'week')
    
  833.     [datetime.date(2005, 2, 14), datetime.date(2005, 3, 14)]
    
  834.     >>> Entry.objects.dates('pub_date', 'day')
    
  835.     [datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]
    
  836.     >>> Entry.objects.dates('pub_date', 'day', order='DESC')
    
  837.     [datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]
    
  838.     >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
    
  839.     [datetime.date(2005, 3, 20)]
    
  840. 
    
  841. ``datetimes()``
    
  842. ~~~~~~~~~~~~~~~
    
  843. 
    
  844. .. method:: datetimes(field_name, kind, order='ASC', tzinfo=None, is_dst=None)
    
  845. 
    
  846. Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.datetime`
    
  847. objects representing all available dates of a particular kind within the
    
  848. contents of the ``QuerySet``.
    
  849. 
    
  850. ``field_name`` should be the name of a ``DateTimeField`` of your model.
    
  851. 
    
  852. ``kind`` should be either ``"year"``, ``"month"``, ``"week"``, ``"day"``,
    
  853. ``"hour"``, ``"minute"``, or ``"second"``. Each :class:`datetime.datetime`
    
  854. object in the result list is "truncated" to the given ``type``.
    
  855. 
    
  856. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
    
  857. ``'DESC'``. This specifies how to order the results.
    
  858. 
    
  859. ``tzinfo`` defines the time zone to which datetimes are converted prior to
    
  860. truncation. Indeed, a given datetime has different representations depending
    
  861. on the time zone in use. This parameter must be a :class:`datetime.tzinfo`
    
  862. object. If it's ``None``, Django uses the :ref:`current time zone
    
  863. <default-current-time-zone>`. It has no effect when :setting:`USE_TZ` is
    
  864. ``False``.
    
  865. 
    
  866. ``is_dst`` indicates whether or not ``pytz`` should interpret nonexistent and
    
  867. ambiguous datetimes in daylight saving time. By default (when ``is_dst=None``),
    
  868. ``pytz`` raises an exception for such datetimes.
    
  869. 
    
  870. .. deprecated:: 4.0
    
  871. 
    
  872.     The ``is_dst`` parameter is deprecated and will be removed in Django 5.0.
    
  873. 
    
  874. .. _database-time-zone-definitions:
    
  875. 
    
  876. .. note::
    
  877. 
    
  878.     This function performs time zone conversions directly in the database.
    
  879.     As a consequence, your database must be able to interpret the value of
    
  880.     ``tzinfo.tzname(None)``. This translates into the following requirements:
    
  881. 
    
  882.     - SQLite: no requirements. Conversions are performed in Python.
    
  883.     - PostgreSQL: no requirements (see `Time Zones`_).
    
  884.     - Oracle: no requirements (see `Choosing a Time Zone File`_).
    
  885.     - MySQL: load the time zone tables with `mysql_tzinfo_to_sql`_.
    
  886. 
    
  887.     .. _Time Zones: https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES
    
  888.     .. _Choosing a Time Zone File: https://docs.oracle.com/en/database/oracle/
    
  889.        oracle-database/18/nlspg/datetime-data-types-and-time-zone-support.html
    
  890.        #GUID-805AB986-DE12-4FEA-AF56-5AABCD2132DF
    
  891.     .. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
    
  892. 
    
  893. ``none()``
    
  894. ~~~~~~~~~~
    
  895. 
    
  896. .. method:: none()
    
  897. 
    
  898. Calling ``none()`` will create a queryset that never returns any objects and no
    
  899. query will be executed when accessing the results. A ``qs.none()`` queryset
    
  900. is an instance of ``EmptyQuerySet``.
    
  901. 
    
  902. Examples::
    
  903. 
    
  904.     >>> Entry.objects.none()
    
  905.     <QuerySet []>
    
  906.     >>> from django.db.models.query import EmptyQuerySet
    
  907.     >>> isinstance(Entry.objects.none(), EmptyQuerySet)
    
  908.     True
    
  909. 
    
  910. ``all()``
    
  911. ~~~~~~~~~
    
  912. 
    
  913. .. method:: all()
    
  914. 
    
  915. Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass).  This
    
  916. can be useful in situations where you might want to pass in either a model
    
  917. manager or a ``QuerySet`` and do further filtering on the result. After calling
    
  918. ``all()`` on either object, you'll definitely have a ``QuerySet`` to work with.
    
  919. 
    
  920. When a ``QuerySet`` is :ref:`evaluated <when-querysets-are-evaluated>`, it
    
  921. typically caches its results. If the data in the database might have changed
    
  922. since a ``QuerySet`` was evaluated, you can get updated results for the same
    
  923. query by calling ``all()`` on a previously evaluated ``QuerySet``.
    
  924. 
    
  925. ``union()``
    
  926. ~~~~~~~~~~~
    
  927. 
    
  928. .. method:: union(*other_qs, all=False)
    
  929. 
    
  930. Uses SQL's ``UNION`` operator to combine the results of two or more
    
  931. ``QuerySet``\s. For example:
    
  932. 
    
  933.     >>> qs1.union(qs2, qs3)
    
  934. 
    
  935. The ``UNION`` operator selects only distinct values by default. To allow
    
  936. duplicate values, use the ``all=True`` argument.
    
  937. 
    
  938. ``union()``, ``intersection()``, and ``difference()`` return model instances
    
  939. of the type of the first ``QuerySet`` even if the arguments are ``QuerySet``\s
    
  940. of other models. Passing different models works as long as the ``SELECT`` list
    
  941. is the same in all ``QuerySet``\s (at least the types, the names don't matter
    
  942. as long as the types are in the same order). In such cases, you must use the
    
  943. column names from the first ``QuerySet`` in ``QuerySet`` methods applied to the
    
  944. resulting ``QuerySet``. For example::
    
  945. 
    
  946.     >>> qs1 = Author.objects.values_list('name')
    
  947.     >>> qs2 = Entry.objects.values_list('headline')
    
  948.     >>> qs1.union(qs2).order_by('name')
    
  949. 
    
  950. In addition, only ``LIMIT``, ``OFFSET``, ``COUNT(*)``, ``ORDER BY``, and
    
  951. specifying columns (i.e. slicing, :meth:`count`, :meth:`exists`,
    
  952. :meth:`order_by`, and :meth:`values()`/:meth:`values_list()`) are allowed
    
  953. on the resulting ``QuerySet``. Further, databases place restrictions on
    
  954. what operations are allowed in the combined queries. For example, most
    
  955. databases don't allow ``LIMIT`` or ``OFFSET`` in the combined queries.
    
  956. 
    
  957. ``intersection()``
    
  958. ~~~~~~~~~~~~~~~~~~
    
  959. 
    
  960. .. method:: intersection(*other_qs)
    
  961. 
    
  962. Uses SQL's ``INTERSECT`` operator to return the shared elements of two or more
    
  963. ``QuerySet``\s. For example:
    
  964. 
    
  965.     >>> qs1.intersection(qs2, qs3)
    
  966. 
    
  967. See :meth:`union` for some restrictions.
    
  968. 
    
  969. ``difference()``
    
  970. ~~~~~~~~~~~~~~~~
    
  971. 
    
  972. .. method:: difference(*other_qs)
    
  973. 
    
  974. Uses SQL's ``EXCEPT`` operator to keep only elements present in the
    
  975. ``QuerySet`` but not in some other ``QuerySet``\s. For example::
    
  976. 
    
  977.     >>> qs1.difference(qs2, qs3)
    
  978. 
    
  979. See :meth:`union` for some restrictions.
    
  980. 
    
  981. ``select_related()``
    
  982. ~~~~~~~~~~~~~~~~~~~~
    
  983. 
    
  984. .. method:: select_related(*fields)
    
  985. 
    
  986. Returns a ``QuerySet`` that will "follow" foreign-key relationships, selecting
    
  987. additional related-object data when it executes its query. This is a
    
  988. performance booster which results in a single more complex query but means
    
  989. later use of foreign-key relationships won't require database queries.
    
  990. 
    
  991. The following examples illustrate the difference between plain lookups and
    
  992. ``select_related()`` lookups. Here's standard lookup::
    
  993. 
    
  994.     # Hits the database.
    
  995.     e = Entry.objects.get(id=5)
    
  996. 
    
  997.     # Hits the database again to get the related Blog object.
    
  998.     b = e.blog
    
  999. 
    
  1000. And here's ``select_related`` lookup::
    
  1001. 
    
  1002.     # Hits the database.
    
  1003.     e = Entry.objects.select_related('blog').get(id=5)
    
  1004. 
    
  1005.     # Doesn't hit the database, because e.blog has been prepopulated
    
  1006.     # in the previous query.
    
  1007.     b = e.blog
    
  1008. 
    
  1009. You can use ``select_related()`` with any queryset of objects::
    
  1010. 
    
  1011.     from django.utils import timezone
    
  1012. 
    
  1013.     # Find all the blogs with entries scheduled to be published in the future.
    
  1014.     blogs = set()
    
  1015. 
    
  1016.     for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):
    
  1017.         # Without select_related(), this would make a database query for each
    
  1018.         # loop iteration in order to fetch the related blog for each entry.
    
  1019.         blogs.add(e.blog)
    
  1020. 
    
  1021. The order of ``filter()`` and ``select_related()`` chaining isn't important.
    
  1022. These querysets are equivalent::
    
  1023. 
    
  1024.     Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')
    
  1025.     Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now())
    
  1026. 
    
  1027. You can follow foreign keys in a similar way to querying them. If you have the
    
  1028. following models::
    
  1029. 
    
  1030.     from django.db import models
    
  1031. 
    
  1032.     class City(models.Model):
    
  1033.         # ...
    
  1034.         pass
    
  1035. 
    
  1036.     class Person(models.Model):
    
  1037.         # ...
    
  1038.         hometown = models.ForeignKey(
    
  1039.             City,
    
  1040.             on_delete=models.SET_NULL,
    
  1041.             blank=True,
    
  1042.             null=True,
    
  1043.         )
    
  1044. 
    
  1045.     class Book(models.Model):
    
  1046.         # ...
    
  1047.         author = models.ForeignKey(Person, on_delete=models.CASCADE)
    
  1048. 
    
  1049. ... then a call to ``Book.objects.select_related('author__hometown').get(id=4)``
    
  1050. will cache the related ``Person`` *and* the related ``City``::
    
  1051. 
    
  1052.     # Hits the database with joins to the author and hometown tables.
    
  1053.     b = Book.objects.select_related('author__hometown').get(id=4)
    
  1054.     p = b.author         # Doesn't hit the database.
    
  1055.     c = p.hometown       # Doesn't hit the database.
    
  1056. 
    
  1057.     # Without select_related()...
    
  1058.     b = Book.objects.get(id=4)  # Hits the database.
    
  1059.     p = b.author         # Hits the database.
    
  1060.     c = p.hometown       # Hits the database.
    
  1061. 
    
  1062. You can refer to any :class:`~django.db.models.ForeignKey` or
    
  1063. :class:`~django.db.models.OneToOneField` relation in the list of fields
    
  1064. passed to ``select_related()``.
    
  1065. 
    
  1066. You can also refer to the reverse direction of a
    
  1067. :class:`~django.db.models.OneToOneField` in the list of fields passed to
    
  1068. ``select_related`` — that is, you can traverse a
    
  1069. :class:`~django.db.models.OneToOneField` back to the object on which the field
    
  1070. is defined. Instead of specifying the field name, use the :attr:`related_name
    
  1071. <django.db.models.ForeignKey.related_name>` for the field on the related object.
    
  1072. 
    
  1073. There may be some situations where you wish to call ``select_related()`` with a
    
  1074. lot of related objects, or where you don't know all of the relations. In these
    
  1075. cases it is possible to call ``select_related()`` with no arguments. This will
    
  1076. follow all non-null foreign keys it can find - nullable foreign keys must be
    
  1077. specified. This is not recommended in most cases as it is likely to make the
    
  1078. underlying query more complex, and return more data, than is actually needed.
    
  1079. 
    
  1080. If you need to clear the list of related fields added by past calls of
    
  1081. ``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
    
  1082. 
    
  1083.    >>> without_relations = queryset.select_related(None)
    
  1084. 
    
  1085. Chaining ``select_related`` calls works in a similar way to other methods -
    
  1086. that is that ``select_related('foo', 'bar')`` is equivalent to
    
  1087. ``select_related('foo').select_related('bar')``.
    
  1088. 
    
  1089. ``prefetch_related()``
    
  1090. ~~~~~~~~~~~~~~~~~~~~~~
    
  1091. 
    
  1092. .. method:: prefetch_related(*lookups)
    
  1093. 
    
  1094. Returns a ``QuerySet`` that will automatically retrieve, in a single batch,
    
  1095. related objects for each of the specified lookups.
    
  1096. 
    
  1097. This has a similar purpose to ``select_related``, in that both are designed to
    
  1098. stop the deluge of database queries that is caused by accessing related objects,
    
  1099. but the strategy is quite different.
    
  1100. 
    
  1101. ``select_related`` works by creating an SQL join and including the fields of the
    
  1102. related object in the ``SELECT`` statement. For this reason, ``select_related``
    
  1103. gets the related objects in the same database query. However, to avoid the much
    
  1104. larger result set that would result from joining across a 'many' relationship,
    
  1105. ``select_related`` is limited to single-valued relationships - foreign key and
    
  1106. one-to-one.
    
  1107. 
    
  1108. ``prefetch_related``, on the other hand, does a separate lookup for each
    
  1109. relationship, and does the 'joining' in Python. This allows it to prefetch
    
  1110. many-to-many and many-to-one objects, which cannot be done using
    
  1111. ``select_related``, in addition to the foreign key and one-to-one relationships
    
  1112. that are supported by ``select_related``. It also supports prefetching of
    
  1113. :class:`~django.contrib.contenttypes.fields.GenericRelation` and
    
  1114. :class:`~django.contrib.contenttypes.fields.GenericForeignKey`, however, it
    
  1115. must be restricted to a homogeneous set of results. For example, prefetching
    
  1116. objects referenced by a ``GenericForeignKey`` is only supported if the query
    
  1117. is restricted to one ``ContentType``.
    
  1118. 
    
  1119. For example, suppose you have these models::
    
  1120. 
    
  1121.     from django.db import models
    
  1122. 
    
  1123.     class Topping(models.Model):
    
  1124.         name = models.CharField(max_length=30)
    
  1125. 
    
  1126.     class Pizza(models.Model):
    
  1127.         name = models.CharField(max_length=50)
    
  1128.         toppings = models.ManyToManyField(Topping)
    
  1129. 
    
  1130.         def __str__(self):
    
  1131.             return "%s (%s)" % (
    
  1132.                 self.name,
    
  1133.                 ", ".join(topping.name for topping in self.toppings.all()),
    
  1134.             )
    
  1135. 
    
  1136. and run::
    
  1137. 
    
  1138.     >>> Pizza.objects.all()
    
  1139.     ["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...
    
  1140. 
    
  1141. The problem with this is that every time ``Pizza.__str__()`` asks for
    
  1142. ``self.toppings.all()`` it has to query the database, so
    
  1143. ``Pizza.objects.all()`` will run a query on the Toppings table for **every**
    
  1144. item in the Pizza ``QuerySet``.
    
  1145. 
    
  1146. We can reduce to just two queries using ``prefetch_related``:
    
  1147. 
    
  1148.     >>> Pizza.objects.prefetch_related('toppings')
    
  1149. 
    
  1150. This implies a ``self.toppings.all()`` for each ``Pizza``; now each time
    
  1151. ``self.toppings.all()`` is called, instead of having to go to the database for
    
  1152. the items, it will find them in a prefetched ``QuerySet`` cache that was
    
  1153. populated in a single query.
    
  1154. 
    
  1155. That is, all the relevant toppings will have been fetched in a single query,
    
  1156. and used to make ``QuerySets`` that have a pre-filled cache of the relevant
    
  1157. results; these ``QuerySets`` are then used in the ``self.toppings.all()`` calls.
    
  1158. 
    
  1159. The additional queries in ``prefetch_related()`` are executed after the
    
  1160. ``QuerySet`` has begun to be evaluated and the primary query has been executed.
    
  1161. 
    
  1162. If you have an iterable of model instances, you can prefetch related attributes
    
  1163. on those instances using the :func:`~django.db.models.prefetch_related_objects`
    
  1164. function.
    
  1165. 
    
  1166. Note that the result cache of the primary ``QuerySet`` and all specified related
    
  1167. objects will then be fully loaded into memory. This changes the typical
    
  1168. behavior of ``QuerySets``, which normally try to avoid loading all objects into
    
  1169. memory before they are needed, even after a query has been executed in the
    
  1170. database.
    
  1171. 
    
  1172. .. note::
    
  1173. 
    
  1174.     Remember that, as always with ``QuerySets``, any subsequent chained methods
    
  1175.     which imply a different database query will ignore previously cached
    
  1176.     results, and retrieve data using a fresh database query. So, if you write
    
  1177.     the following:
    
  1178. 
    
  1179.         >>> pizzas = Pizza.objects.prefetch_related('toppings')
    
  1180.         >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas]
    
  1181. 
    
  1182.     ...then the fact that ``pizza.toppings.all()`` has been prefetched will not
    
  1183.     help you. The ``prefetch_related('toppings')`` implied
    
  1184.     ``pizza.toppings.all()``, but ``pizza.toppings.filter()`` is a new and
    
  1185.     different query. The prefetched cache can't help here; in fact it hurts
    
  1186.     performance, since you have done a database query that you haven't used. So
    
  1187.     use this feature with caution!
    
  1188. 
    
  1189.     Also, if you call the database-altering methods
    
  1190.     :meth:`~django.db.models.fields.related.RelatedManager.add`,
    
  1191.     :meth:`~django.db.models.fields.related.RelatedManager.remove`,
    
  1192.     :meth:`~django.db.models.fields.related.RelatedManager.clear` or
    
  1193.     :meth:`~django.db.models.fields.related.RelatedManager.set`, on
    
  1194.     :class:`related managers<django.db.models.fields.related.RelatedManager>`,
    
  1195.     any prefetched cache for the relation will be cleared.
    
  1196. 
    
  1197. You can also use the normal join syntax to do related fields of related
    
  1198. fields. Suppose we have an additional model to the example above::
    
  1199. 
    
  1200.     class Restaurant(models.Model):
    
  1201.         pizzas = models.ManyToManyField(Pizza, related_name='restaurants')
    
  1202.         best_pizza = models.ForeignKey(Pizza, related_name='championed_by', on_delete=models.CASCADE)
    
  1203. 
    
  1204. The following are all legal:
    
  1205. 
    
  1206.     >>> Restaurant.objects.prefetch_related('pizzas__toppings')
    
  1207. 
    
  1208. This will prefetch all pizzas belonging to restaurants, and all toppings
    
  1209. belonging to those pizzas. This will result in a total of 3 database queries -
    
  1210. one for the restaurants, one for the pizzas, and one for the toppings.
    
  1211. 
    
  1212.     >>> Restaurant.objects.prefetch_related('best_pizza__toppings')
    
  1213. 
    
  1214. This will fetch the best pizza and all the toppings for the best pizza for each
    
  1215. restaurant. This will be done in 3 database queries - one for the restaurants,
    
  1216. one for the 'best pizzas', and one for the toppings.
    
  1217. 
    
  1218. The ``best_pizza`` relationship could also be fetched using ``select_related``
    
  1219. to reduce the query count to 2::
    
  1220. 
    
  1221.     >>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')
    
  1222. 
    
  1223. Since the prefetch is executed after the main query (which includes the joins
    
  1224. needed by ``select_related``), it is able to detect that the ``best_pizza``
    
  1225. objects have already been fetched, and it will skip fetching them again.
    
  1226. 
    
  1227. Chaining ``prefetch_related`` calls will accumulate the lookups that are
    
  1228. prefetched. To clear any ``prefetch_related`` behavior, pass ``None`` as a
    
  1229. parameter:
    
  1230. 
    
  1231.    >>> non_prefetched = qs.prefetch_related(None)
    
  1232. 
    
  1233. One difference to note when using ``prefetch_related`` is that objects created
    
  1234. by a query can be shared between the different objects that they are related to
    
  1235. i.e. a single Python model instance can appear at more than one point in the
    
  1236. tree of objects that are returned. This will normally happen with foreign key
    
  1237. relationships. Typically this behavior will not be a problem, and will in fact
    
  1238. save both memory and CPU time.
    
  1239. 
    
  1240. While ``prefetch_related`` supports prefetching ``GenericForeignKey``
    
  1241. relationships, the number of queries will depend on the data. Since a
    
  1242. ``GenericForeignKey`` can reference data in multiple tables, one query per table
    
  1243. referenced is needed, rather than one query for all the items. There could be
    
  1244. additional queries on the ``ContentType`` table if the relevant rows have not
    
  1245. already been fetched.
    
  1246. 
    
  1247. ``prefetch_related`` in most cases will be implemented using an SQL query that
    
  1248. uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause
    
  1249. could be generated, which, depending on the database, might have performance
    
  1250. problems of its own when it comes to parsing or executing the SQL query. Always
    
  1251. profile for your use case!
    
  1252. 
    
  1253. .. versionchanged:: 4.1
    
  1254. 
    
  1255.     If you use ``iterator()`` to run the query, ``prefetch_related()``
    
  1256.     calls will only be observed if a value for ``chunk_size`` is provided.
    
  1257. 
    
  1258. You can use the :class:`~django.db.models.Prefetch` object to further control
    
  1259. the prefetch operation.
    
  1260. 
    
  1261. In its simplest form ``Prefetch`` is equivalent to the traditional string based
    
  1262. lookups:
    
  1263. 
    
  1264.     >>> from django.db.models import Prefetch
    
  1265.     >>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings'))
    
  1266. 
    
  1267. You can provide a custom queryset with the optional ``queryset`` argument.
    
  1268. This can be used to change the default ordering of the queryset:
    
  1269. 
    
  1270.     >>> Restaurant.objects.prefetch_related(
    
  1271.     ...     Prefetch('pizzas__toppings', queryset=Toppings.objects.order_by('name')))
    
  1272. 
    
  1273. Or to call :meth:`~django.db.models.query.QuerySet.select_related()` when
    
  1274. applicable to reduce the number of queries even further:
    
  1275. 
    
  1276.     >>> Pizza.objects.prefetch_related(
    
  1277.     ...     Prefetch('restaurants', queryset=Restaurant.objects.select_related('best_pizza')))
    
  1278. 
    
  1279. You can also assign the prefetched result to a custom attribute with the optional
    
  1280. ``to_attr`` argument. The result will be stored directly in a list.
    
  1281. 
    
  1282. This allows prefetching the same relation multiple times with a different
    
  1283. ``QuerySet``; for instance:
    
  1284. 
    
  1285.     >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)
    
  1286.     >>> Restaurant.objects.prefetch_related(
    
  1287.     ...     Prefetch('pizzas', to_attr='menu'),
    
  1288.     ...     Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'))
    
  1289. 
    
  1290. Lookups created with custom ``to_attr`` can still be traversed as usual by other
    
  1291. lookups:
    
  1292. 
    
  1293.     >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)
    
  1294.     >>> Restaurant.objects.prefetch_related(
    
  1295.     ...     Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'),
    
  1296.     ...     'vegetarian_menu__toppings')
    
  1297. 
    
  1298. Using ``to_attr`` is recommended when filtering down the prefetch result as it is
    
  1299. less ambiguous than storing a filtered result in the related manager's cache:
    
  1300. 
    
  1301.     >>> queryset = Pizza.objects.filter(vegetarian=True)
    
  1302.     >>>
    
  1303.     >>> # Recommended:
    
  1304.     >>> restaurants = Restaurant.objects.prefetch_related(
    
  1305.     ...     Prefetch('pizzas', queryset=queryset, to_attr='vegetarian_pizzas'))
    
  1306.     >>> vegetarian_pizzas = restaurants[0].vegetarian_pizzas
    
  1307.     >>>
    
  1308.     >>> # Not recommended:
    
  1309.     >>> restaurants = Restaurant.objects.prefetch_related(
    
  1310.     ...     Prefetch('pizzas', queryset=queryset))
    
  1311.     >>> vegetarian_pizzas = restaurants[0].pizzas.all()
    
  1312. 
    
  1313. Custom prefetching also works with single related relations like
    
  1314. forward ``ForeignKey`` or ``OneToOneField``. Generally you'll want to use
    
  1315. :meth:`select_related()` for these relations, but there are a number of cases
    
  1316. where prefetching with a custom ``QuerySet`` is useful:
    
  1317. 
    
  1318. * You want to use a ``QuerySet`` that performs further prefetching
    
  1319.   on related models.
    
  1320. 
    
  1321. * You want to prefetch only a subset of the related objects.
    
  1322. 
    
  1323. * You want to use performance optimization techniques like
    
  1324.   :meth:`deferred fields <defer()>`:
    
  1325. 
    
  1326.     >>> queryset = Pizza.objects.only('name')
    
  1327.     >>>
    
  1328.     >>> restaurants = Restaurant.objects.prefetch_related(
    
  1329.     ...     Prefetch('best_pizza', queryset=queryset))
    
  1330. 
    
  1331. When using multiple databases, ``Prefetch`` will respect your choice of
    
  1332. database. If the inner query does not specify a database, it will use the
    
  1333. database selected by the outer query. All of the following are valid::
    
  1334. 
    
  1335.     >>> # Both inner and outer queries will use the 'replica' database
    
  1336.     >>> Restaurant.objects.prefetch_related('pizzas__toppings').using('replica')
    
  1337.     >>> Restaurant.objects.prefetch_related(
    
  1338.     ...     Prefetch('pizzas__toppings'),
    
  1339.     ... ).using('replica')
    
  1340.     >>>
    
  1341.     >>> # Inner will use the 'replica' database; outer will use 'default' database
    
  1342.     >>> Restaurant.objects.prefetch_related(
    
  1343.     ...     Prefetch('pizzas__toppings', queryset=Toppings.objects.using('replica')),
    
  1344.     ... )
    
  1345.     >>>
    
  1346.     >>> # Inner will use 'replica' database; outer will use 'cold-storage' database
    
  1347.     >>> Restaurant.objects.prefetch_related(
    
  1348.     ...     Prefetch('pizzas__toppings', queryset=Toppings.objects.using('replica')),
    
  1349.     ... ).using('cold-storage')
    
  1350. 
    
  1351. .. note::
    
  1352. 
    
  1353.     The ordering of lookups matters.
    
  1354. 
    
  1355.     Take the following examples:
    
  1356. 
    
  1357.        >>> prefetch_related('pizzas__toppings', 'pizzas')
    
  1358. 
    
  1359.     This works even though it's unordered because ``'pizzas__toppings'``
    
  1360.     already contains all the needed information, therefore the second argument
    
  1361.     ``'pizzas'`` is actually redundant.
    
  1362. 
    
  1363.         >>> prefetch_related('pizzas__toppings', Prefetch('pizzas', queryset=Pizza.objects.all()))
    
  1364. 
    
  1365.     This will raise a ``ValueError`` because of the attempt to redefine the
    
  1366.     queryset of a previously seen lookup. Note that an implicit queryset was
    
  1367.     created to traverse ``'pizzas'`` as part of the ``'pizzas__toppings'``
    
  1368.     lookup.
    
  1369. 
    
  1370.         >>> prefetch_related('pizza_list__toppings', Prefetch('pizzas', to_attr='pizza_list'))
    
  1371. 
    
  1372.     This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't exist yet
    
  1373.     when ``'pizza_list__toppings'`` is being processed.
    
  1374. 
    
  1375.     This consideration is not limited to the use of ``Prefetch`` objects. Some
    
  1376.     advanced techniques may require that the lookups be performed in a
    
  1377.     specific order to avoid creating extra queries; therefore it's recommended
    
  1378.     to always carefully order ``prefetch_related`` arguments.
    
  1379. 
    
  1380. ``extra()``
    
  1381. ~~~~~~~~~~~
    
  1382. 
    
  1383. .. method:: extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    
  1384. 
    
  1385. Sometimes, the Django query syntax by itself can't easily express a complex
    
  1386. ``WHERE`` clause. For these edge cases, Django provides the ``extra()``
    
  1387. ``QuerySet`` modifier — a hook for injecting specific clauses into the SQL
    
  1388. generated by a ``QuerySet``.
    
  1389. 
    
  1390. .. admonition:: Use this method as a last resort
    
  1391. 
    
  1392.     This is an old API that we aim to deprecate at some point in the future.
    
  1393.     Use it only if you cannot express your query using other queryset methods.
    
  1394.     If you do need to use it, please `file a ticket
    
  1395.     <https://code.djangoproject.com/newticket>`_ using the `QuerySet.extra
    
  1396.     keyword <https://code.djangoproject.com/query?status=assigned&status=new&keywords=~QuerySet.extra>`_
    
  1397.     with your use case (please check the list of existing tickets first) so
    
  1398.     that we can enhance the QuerySet API to allow removing ``extra()``. We are
    
  1399.     no longer improving or fixing bugs for this method.
    
  1400. 
    
  1401.     For example, this use of ``extra()``::
    
  1402. 
    
  1403.         >>> qs.extra(
    
  1404.         ...     select={'val': "select col from sometable where othercol = %s"},
    
  1405.         ...     select_params=(someparam,),
    
  1406.         ... )
    
  1407. 
    
  1408.     is equivalent to::
    
  1409. 
    
  1410.         >>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,)))
    
  1411. 
    
  1412.     The main benefit of using :class:`~django.db.models.expressions.RawSQL` is
    
  1413.     that you can set ``output_field`` if needed. The main downside is that if
    
  1414.     you refer to some table alias of the queryset in the raw SQL, then it is
    
  1415.     possible that Django might change that alias (for example, when the
    
  1416.     queryset is used as a subquery in yet another query).
    
  1417. 
    
  1418. .. warning::
    
  1419. 
    
  1420.     You should be very careful whenever you use ``extra()``. Every time you use
    
  1421.     it, you should escape any parameters that the user can control by using
    
  1422.     ``params`` in order to protect against SQL injection attacks.
    
  1423. 
    
  1424.     You also must not quote placeholders in the SQL string. This example is
    
  1425.     vulnerable to SQL injection because of the quotes around ``%s``:
    
  1426. 
    
  1427.     .. code-block:: sql
    
  1428. 
    
  1429.         SELECT col FROM sometable WHERE othercol = '%s'  # unsafe!
    
  1430. 
    
  1431.     You can read more about how Django's :ref:`SQL injection protection
    
  1432.     <sql-injection-protection>` works.
    
  1433. 
    
  1434. By definition, these extra lookups may not be portable to different database
    
  1435. engines (because you're explicitly writing SQL code) and violate the DRY
    
  1436. principle, so you should avoid them if possible.
    
  1437. 
    
  1438. Specify one or more of ``params``, ``select``, ``where`` or ``tables``. None
    
  1439. of the arguments is required, but you should use at least one of them.
    
  1440. 
    
  1441. * ``select``
    
  1442. 
    
  1443.   The ``select`` argument lets you put extra fields in the ``SELECT``
    
  1444.   clause.  It should be a dictionary mapping attribute names to SQL
    
  1445.   clauses to use to calculate that attribute.
    
  1446. 
    
  1447.   Example::
    
  1448. 
    
  1449.       Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
    
  1450. 
    
  1451.   As a result, each ``Entry`` object will have an extra attribute,
    
  1452.   ``is_recent``, a boolean representing whether the entry's ``pub_date``
    
  1453.   is greater than Jan. 1, 2006.
    
  1454. 
    
  1455.   Django inserts the given SQL snippet directly into the ``SELECT``
    
  1456.   statement, so the resulting SQL of the above example would be something like:
    
  1457. 
    
  1458.   .. code-block:: sql
    
  1459. 
    
  1460.       SELECT blog_entry.*, (pub_date > '2006-01-01') AS is_recent
    
  1461.       FROM blog_entry;
    
  1462. 
    
  1463. 
    
  1464.   The next example is more advanced; it does a subquery to give each
    
  1465.   resulting ``Blog`` object an ``entry_count`` attribute, an integer count
    
  1466.   of associated ``Entry`` objects::
    
  1467. 
    
  1468.       Blog.objects.extra(
    
  1469.           select={
    
  1470.               'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
    
  1471.           },
    
  1472.       )
    
  1473. 
    
  1474.   In this particular case, we're exploiting the fact that the query will
    
  1475.   already contain the ``blog_blog`` table in its ``FROM`` clause.
    
  1476. 
    
  1477.   The resulting SQL of the above example would be:
    
  1478. 
    
  1479.   .. code-block:: sql
    
  1480. 
    
  1481.       SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id) AS entry_count
    
  1482.       FROM blog_blog;
    
  1483. 
    
  1484.   Note that the parentheses required by most database engines around
    
  1485.   subqueries are not required in Django's ``select`` clauses. Also note
    
  1486.   that some database backends, such as some MySQL versions, don't support
    
  1487.   subqueries.
    
  1488. 
    
  1489.   In some rare cases, you might wish to pass parameters to the SQL
    
  1490.   fragments in ``extra(select=...)``. For this purpose, use the
    
  1491.   ``select_params`` parameter.
    
  1492. 
    
  1493.   This will work, for example::
    
  1494. 
    
  1495.       Blog.objects.extra(
    
  1496.           select={'a': '%s', 'b': '%s'},
    
  1497.           select_params=('one', 'two'),
    
  1498.       )
    
  1499. 
    
  1500.   If you need to use a literal ``%s`` inside your select string, use
    
  1501.   the sequence ``%%s``.
    
  1502. 
    
  1503. * ``where`` / ``tables``
    
  1504. 
    
  1505.   You can define explicit SQL ``WHERE`` clauses — perhaps to perform
    
  1506.   non-explicit joins — by using ``where``. You can manually add tables to
    
  1507.   the SQL ``FROM`` clause by using ``tables``.
    
  1508. 
    
  1509.   ``where`` and ``tables`` both take a list of strings. All ``where``
    
  1510.   parameters are "AND"ed to any other search criteria.
    
  1511. 
    
  1512.   Example::
    
  1513. 
    
  1514.       Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
    
  1515. 
    
  1516.   ...translates (roughly) into the following SQL:
    
  1517. 
    
  1518.   .. code-block:: sql
    
  1519. 
    
  1520.       SELECT * FROM blog_entry WHERE (foo='a' OR bar='a') AND (baz='a')
    
  1521. 
    
  1522.   Be careful when using the ``tables`` parameter if you're specifying
    
  1523.   tables that are already used in the query. When you add extra tables
    
  1524.   via the ``tables`` parameter, Django assumes you want that table
    
  1525.   included an extra time, if it is already included. That creates a
    
  1526.   problem, since the table name will then be given an alias. If a table
    
  1527.   appears multiple times in an SQL statement, the second and subsequent
    
  1528.   occurrences must use aliases so the database can tell them apart. If
    
  1529.   you're referring to the extra table you added in the extra ``where``
    
  1530.   parameter this is going to cause errors.
    
  1531. 
    
  1532.   Normally you'll only be adding extra tables that don't already appear
    
  1533.   in the query. However, if the case outlined above does occur, there are
    
  1534.   a few solutions. First, see if you can get by without including the
    
  1535.   extra table and use the one already in the query. If that isn't
    
  1536.   possible, put your ``extra()`` call at the front of the queryset
    
  1537.   construction so that your table is the first use of that table.
    
  1538.   Finally, if all else fails, look at the query produced and rewrite your
    
  1539.   ``where`` addition to use the alias given to your extra table. The
    
  1540.   alias will be the same each time you construct the queryset in the same
    
  1541.   way, so you can rely upon the alias name to not change.
    
  1542. 
    
  1543. * ``order_by``
    
  1544. 
    
  1545.   If you need to order the resulting queryset using some of the new
    
  1546.   fields or tables you have included via ``extra()`` use the ``order_by``
    
  1547.   parameter to ``extra()`` and pass in a sequence of strings. These
    
  1548.   strings should either be model fields (as in the normal
    
  1549.   :meth:`order_by()` method on querysets), of the form
    
  1550.   ``table_name.column_name`` or an alias for a column that you specified
    
  1551.   in the ``select`` parameter to ``extra()``.
    
  1552. 
    
  1553.   For example::
    
  1554. 
    
  1555.       q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
    
  1556.       q = q.extra(order_by = ['-is_recent'])
    
  1557. 
    
  1558.   This would sort all the items for which ``is_recent`` is true to the
    
  1559.   front of the result set (``True`` sorts before ``False`` in a
    
  1560.   descending ordering).
    
  1561. 
    
  1562.   This shows, by the way, that you can make multiple calls to ``extra()``
    
  1563.   and it will behave as you expect (adding new constraints each time).
    
  1564. 
    
  1565. * ``params``
    
  1566. 
    
  1567.   The ``where`` parameter described above may use standard Python
    
  1568.   database string placeholders — ``'%s'`` to indicate parameters the
    
  1569.   database engine should automatically quote. The ``params`` argument is
    
  1570.   a list of any extra parameters to be substituted.
    
  1571. 
    
  1572.   Example::
    
  1573. 
    
  1574.       Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
    
  1575. 
    
  1576.   Always use ``params`` instead of embedding values directly into
    
  1577.   ``where`` because ``params`` will ensure values are quoted correctly
    
  1578.   according to your particular backend. For example, quotes will be
    
  1579.   escaped correctly.
    
  1580. 
    
  1581.   Bad::
    
  1582. 
    
  1583.       Entry.objects.extra(where=["headline='Lennon'"])
    
  1584. 
    
  1585.   Good::
    
  1586. 
    
  1587.       Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
    
  1588. 
    
  1589. .. warning::
    
  1590. 
    
  1591.     If you are performing queries on MySQL, note that MySQL's silent type coercion
    
  1592.     may cause unexpected results when mixing types. If you query on a string
    
  1593.     type column, but with an integer value, MySQL will coerce the types of all values
    
  1594.     in the table to an integer before performing the comparison. For example, if your
    
  1595.     table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
    
  1596.     both rows will match. To prevent this, perform the correct typecasting
    
  1597.     before using the value in a query.
    
  1598. 
    
  1599. ``defer()``
    
  1600. ~~~~~~~~~~~
    
  1601. 
    
  1602. .. method:: defer(*fields)
    
  1603. 
    
  1604. In some complex data-modeling situations, your models might contain a lot of
    
  1605. fields, some of which could contain a lot of data (for example, text fields),
    
  1606. or require expensive processing to convert them to Python objects. If you are
    
  1607. using the results of a queryset in some situation where you don't know
    
  1608. if you need those particular fields when you initially fetch the data, you can
    
  1609. tell Django not to retrieve them from the database.
    
  1610. 
    
  1611. This is done by passing the names of the fields to not load to ``defer()``::
    
  1612. 
    
  1613.     Entry.objects.defer("headline", "body")
    
  1614. 
    
  1615. A queryset that has deferred fields will still return model instances. Each
    
  1616. deferred field will be retrieved from the database if you access that field
    
  1617. (one at a time, not all the deferred fields at once).
    
  1618. 
    
  1619. .. note::
    
  1620. 
    
  1621.     Deferred fields will not lazy-load like this from asynchronous code.
    
  1622.     Instead, you will get a ``SynchronousOnlyOperation`` exception. If you are
    
  1623.     writing asynchronous code, you should not try to access any fields that you
    
  1624.     ``defer()``.
    
  1625. 
    
  1626. You can make multiple calls to ``defer()``. Each call adds new fields to the
    
  1627. deferred set::
    
  1628. 
    
  1629.     # Defers both the body and headline fields.
    
  1630.     Entry.objects.defer("body").filter(rating=5).defer("headline")
    
  1631. 
    
  1632. The order in which fields are added to the deferred set does not matter.
    
  1633. Calling ``defer()`` with a field name that has already been deferred is
    
  1634. harmless (the field will still be deferred).
    
  1635. 
    
  1636. You can defer loading of fields in related models (if the related models are
    
  1637. loading via :meth:`select_related()`) by using the standard double-underscore
    
  1638. notation to separate related fields::
    
  1639. 
    
  1640.     Blog.objects.select_related().defer("entry__headline", "entry__body")
    
  1641. 
    
  1642. If you want to clear the set of deferred fields, pass ``None`` as a parameter
    
  1643. to ``defer()``::
    
  1644. 
    
  1645.     # Load all fields immediately.
    
  1646.     my_queryset.defer(None)
    
  1647. 
    
  1648. Some fields in a model won't be deferred, even if you ask for them. You can
    
  1649. never defer the loading of the primary key. If you are using
    
  1650. :meth:`select_related()` to retrieve related models, you shouldn't defer the
    
  1651. loading of the field that connects from the primary model to the related
    
  1652. one, doing so will result in an error.
    
  1653. 
    
  1654. .. note::
    
  1655. 
    
  1656.     The ``defer()`` method (and its cousin, :meth:`only()`, below) are only for
    
  1657.     advanced use-cases. They provide an optimization for when you have analyzed
    
  1658.     your queries closely and understand *exactly* what information you need and
    
  1659.     have measured that the difference between returning the fields you need and
    
  1660.     the full set of fields for the model will be significant.
    
  1661. 
    
  1662.     Even if you think you are in the advanced use-case situation, **only use**
    
  1663.     ``defer()`` **when you cannot, at queryset load time, determine if you will
    
  1664.     need the extra fields or not**. If you are frequently loading and using a
    
  1665.     particular subset of your data, the best choice you can make is to
    
  1666.     normalize your models and put the non-loaded data into a separate model
    
  1667.     (and database table). If the columns *must* stay in the one table for some
    
  1668.     reason, create a model with ``Meta.managed = False`` (see the
    
  1669.     :attr:`managed attribute <django.db.models.Options.managed>` documentation)
    
  1670.     containing just the fields you normally need to load and use that where you
    
  1671.     might otherwise call ``defer()``. This makes your code more explicit to the
    
  1672.     reader, is slightly faster and consumes a little less memory in the Python
    
  1673.     process.
    
  1674. 
    
  1675.     For example, both of these models use the same underlying database table::
    
  1676. 
    
  1677.         class CommonlyUsedModel(models.Model):
    
  1678.             f1 = models.CharField(max_length=10)
    
  1679. 
    
  1680.             class Meta:
    
  1681.                 managed = False
    
  1682.                 db_table = 'app_largetable'
    
  1683. 
    
  1684.         class ManagedModel(models.Model):
    
  1685.             f1 = models.CharField(max_length=10)
    
  1686.             f2 = models.CharField(max_length=10)
    
  1687. 
    
  1688.             class Meta:
    
  1689.                 db_table = 'app_largetable'
    
  1690. 
    
  1691.         # Two equivalent QuerySets:
    
  1692.         CommonlyUsedModel.objects.all()
    
  1693.         ManagedModel.objects.defer('f2')
    
  1694. 
    
  1695.     If many fields need to be duplicated in the unmanaged model, it may be best
    
  1696.     to create an abstract model with the shared fields and then have the
    
  1697.     unmanaged and managed models inherit from the abstract model.
    
  1698. 
    
  1699. .. note::
    
  1700. 
    
  1701.     When calling :meth:`~django.db.models.Model.save()` for instances with
    
  1702.     deferred fields, only the loaded fields will be saved. See
    
  1703.     :meth:`~django.db.models.Model.save()` for more details.
    
  1704. 
    
  1705. ``only()``
    
  1706. ~~~~~~~~~~
    
  1707. 
    
  1708. .. method:: only(*fields)
    
  1709. 
    
  1710. The ``only()`` method is essentially the opposite of :meth:`defer`. Only the
    
  1711. fields passed into this method and that are *not* already specified as deferred
    
  1712. are loaded immediately when the queryset is evaluated.
    
  1713. 
    
  1714. If you have a model where almost all the fields need to be deferred, using
    
  1715. ``only()`` to specify the complementary set of fields can result in simpler
    
  1716. code.
    
  1717. 
    
  1718. Suppose you have a model with fields ``name``, ``age`` and ``biography``. The
    
  1719. following two querysets are the same, in terms of deferred fields::
    
  1720. 
    
  1721.     Person.objects.defer("age", "biography")
    
  1722.     Person.objects.only("name")
    
  1723. 
    
  1724. Whenever you call ``only()`` it *replaces* the set of fields to load
    
  1725. immediately. The method's name is mnemonic: **only** those fields are loaded
    
  1726. immediately; the remainder are deferred. Thus, successive calls to ``only()``
    
  1727. result in only the final fields being considered::
    
  1728. 
    
  1729.     # This will defer all fields except the headline.
    
  1730.     Entry.objects.only("body", "rating").only("headline")
    
  1731. 
    
  1732. Since ``defer()`` acts incrementally (adding fields to the deferred list), you
    
  1733. can combine calls to ``only()`` and ``defer()`` and things will behave
    
  1734. logically::
    
  1735. 
    
  1736.     # Final result is that everything except "headline" is deferred.
    
  1737.     Entry.objects.only("headline", "body").defer("body")
    
  1738. 
    
  1739.     # Final result loads headline immediately.
    
  1740.     Entry.objects.defer("body").only("headline", "body")
    
  1741. 
    
  1742. All of the cautions in the note for the :meth:`defer` documentation apply to
    
  1743. ``only()`` as well. Use it cautiously and only after exhausting your other
    
  1744. options.
    
  1745. 
    
  1746. Using :meth:`only` and omitting a field requested using :meth:`select_related`
    
  1747. is an error as well.
    
  1748. 
    
  1749. As with ``defer()``, you cannot access the non-loaded fields from asynchronous
    
  1750. code and expect them to load. Instead, you will get a
    
  1751. ``SynchronousOnlyOperation`` exception. Ensure that all fields you might access
    
  1752. are in your ``only()`` call.
    
  1753. 
    
  1754. .. note::
    
  1755. 
    
  1756.     When calling :meth:`~django.db.models.Model.save()` for instances with
    
  1757.     deferred fields, only the loaded fields will be saved. See
    
  1758.     :meth:`~django.db.models.Model.save()` for more details.
    
  1759. 
    
  1760. .. note::
    
  1761. 
    
  1762.     When using :meth:`defer` after ``only()`` the fields in :meth:`defer` will
    
  1763.     override ``only()`` for fields that are listed in both.
    
  1764. 
    
  1765. ``using()``
    
  1766. ~~~~~~~~~~~
    
  1767. 
    
  1768. .. method:: using(alias)
    
  1769. 
    
  1770. This method is for controlling which database the ``QuerySet`` will be
    
  1771. evaluated against if you are using more than one database.  The only argument
    
  1772. this method takes is the alias of a database, as defined in
    
  1773. :setting:`DATABASES`.
    
  1774. 
    
  1775. For example::
    
  1776. 
    
  1777.     # queries the database with the 'default' alias.
    
  1778.     >>> Entry.objects.all()
    
  1779. 
    
  1780.     # queries the database with the 'backup' alias
    
  1781.     >>> Entry.objects.using('backup')
    
  1782. 
    
  1783. ``select_for_update()``
    
  1784. ~~~~~~~~~~~~~~~~~~~~~~~
    
  1785. 
    
  1786. .. method:: select_for_update(nowait=False, skip_locked=False, of=(), no_key=False)
    
  1787. 
    
  1788. Returns a queryset that will lock rows until the end of the transaction,
    
  1789. generating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases.
    
  1790. 
    
  1791. For example::
    
  1792. 
    
  1793.     from django.db import transaction
    
  1794. 
    
  1795.     entries = Entry.objects.select_for_update().filter(author=request.user)
    
  1796.     with transaction.atomic():
    
  1797.         for entry in entries:
    
  1798.             ...
    
  1799. 
    
  1800. When the queryset is evaluated (``for entry in entries`` in this case), all
    
  1801. matched entries will be locked until the end of the transaction block, meaning
    
  1802. that other transactions will be prevented from changing or acquiring locks on
    
  1803. them.
    
  1804. 
    
  1805. Usually, if another transaction has already acquired a lock on one of the
    
  1806. selected rows, the query will block until the lock is released. If this is
    
  1807. not the behavior you want, call ``select_for_update(nowait=True)``. This will
    
  1808. make the call non-blocking. If a conflicting lock is already acquired by
    
  1809. another transaction, :exc:`~django.db.DatabaseError` will be raised when the
    
  1810. queryset is evaluated. You can also ignore locked rows by using
    
  1811. ``select_for_update(skip_locked=True)`` instead. The ``nowait`` and
    
  1812. ``skip_locked`` are mutually exclusive and attempts to call
    
  1813. ``select_for_update()`` with both options enabled will result in a
    
  1814. :exc:`ValueError`.
    
  1815. 
    
  1816. By default, ``select_for_update()`` locks all rows that are selected by the
    
  1817. query. For example, rows of related objects specified in :meth:`select_related`
    
  1818. are locked in addition to rows of the queryset's model. If this isn't desired,
    
  1819. specify the related objects you want to lock in ``select_for_update(of=(...))``
    
  1820. using the same fields syntax as :meth:`select_related`. Use the value ``'self'``
    
  1821. to refer to the queryset's model.
    
  1822. 
    
  1823. .. admonition:: Lock parents models in ``select_for_update(of=(...))``
    
  1824. 
    
  1825.     If you want to lock parents models when using :ref:`multi-table inheritance
    
  1826.     <multi-table-inheritance>`, you must specify parent link fields (by default
    
  1827.     ``<parent_model_name>_ptr``) in the ``of`` argument. For example::
    
  1828. 
    
  1829.         Restaurant.objects.select_for_update(of=('self', 'place_ptr'))
    
  1830. 
    
  1831. .. admonition:: Using ``select_for_update(of=(...))`` with specified fields
    
  1832. 
    
  1833.     If you want to lock models and specify selected fields, e.g. using
    
  1834.     :meth:`values`, you must select at least one field from each model in the
    
  1835.     ``of`` argument. Models without selected fields will not be locked.
    
  1836. 
    
  1837. On PostgreSQL only, you can pass ``no_key=True`` in order to acquire a weaker
    
  1838. lock, that still allows creating rows that merely reference locked rows
    
  1839. (through a foreign key, for example) while the lock is in place. The
    
  1840. PostgreSQL documentation has more details about `row-level lock modes
    
  1841. <https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS>`_.
    
  1842. 
    
  1843. You can't use ``select_for_update()`` on nullable relations::
    
  1844. 
    
  1845.     >>> Person.objects.select_related('hometown').select_for_update()
    
  1846.     Traceback (most recent call last):
    
  1847.     ...
    
  1848.     django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join
    
  1849. 
    
  1850. To avoid that restriction, you can exclude null objects if you don't care about
    
  1851. them::
    
  1852. 
    
  1853.     >>> Person.objects.select_related('hometown').select_for_update().exclude(hometown=None)
    
  1854.     <QuerySet [<Person: ...)>, ...]>
    
  1855. 
    
  1856. The ``postgresql``, ``oracle``, and ``mysql`` database backends support
    
  1857. ``select_for_update()``. However, MariaDB only supports the ``nowait``
    
  1858. argument, MariaDB 10.6+ also supports the ``skip_locked`` argument, and MySQL
    
  1859. 8.0.1+ supports the ``nowait``, ``skip_locked``, and ``of`` arguments. The
    
  1860. ``no_key`` argument is only supported on PostgreSQL.
    
  1861. 
    
  1862. Passing ``nowait=True``, ``skip_locked=True``, ``no_key=True``, or ``of`` to
    
  1863. ``select_for_update()`` using database backends that do not support these
    
  1864. options, such as MySQL, raises a :exc:`~django.db.NotSupportedError`. This
    
  1865. prevents code from unexpectedly blocking.
    
  1866. 
    
  1867. Evaluating a queryset with ``select_for_update()`` in autocommit mode on
    
  1868. backends which support ``SELECT ... FOR UPDATE`` is a
    
  1869. :exc:`~django.db.transaction.TransactionManagementError` error because the
    
  1870. rows are not locked in that case. If allowed, this would facilitate data
    
  1871. corruption and could easily be caused by calling code that expects to be run in
    
  1872. a transaction outside of one.
    
  1873. 
    
  1874. Using ``select_for_update()`` on backends which do not support
    
  1875. ``SELECT ... FOR UPDATE`` (such as SQLite) will have no effect.
    
  1876. ``SELECT ... FOR UPDATE`` will not be added to the query, and an error isn't
    
  1877. raised if ``select_for_update()`` is used in autocommit mode.
    
  1878. 
    
  1879. .. warning::
    
  1880. 
    
  1881.     Although ``select_for_update()`` normally fails in autocommit mode, since
    
  1882.     :class:`~django.test.TestCase` automatically wraps each test in a
    
  1883.     transaction, calling ``select_for_update()`` in a ``TestCase`` even outside
    
  1884.     an :func:`~django.db.transaction.atomic()` block will (perhaps unexpectedly)
    
  1885.     pass without raising a ``TransactionManagementError``. To properly test
    
  1886.     ``select_for_update()`` you should use
    
  1887.     :class:`~django.test.TransactionTestCase`.
    
  1888. 
    
  1889. .. admonition:: Certain expressions may not be supported
    
  1890. 
    
  1891.     PostgreSQL doesn't support ``select_for_update()`` with
    
  1892.     :class:`~django.db.models.expressions.Window` expressions.
    
  1893. 
    
  1894. .. versionchanged:: 4.0
    
  1895. 
    
  1896.     The ``skip_locked`` argument was allowed on MariaDB 10.6+.
    
  1897. 
    
  1898. ``raw()``
    
  1899. ~~~~~~~~~
    
  1900. 
    
  1901. .. method:: raw(raw_query, params=(), translations=None, using=None)
    
  1902. 
    
  1903. Takes a raw SQL query, executes it, and returns a
    
  1904. ``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
    
  1905. can be iterated over just like a normal ``QuerySet`` to provide object
    
  1906. instances.
    
  1907. 
    
  1908. See the :doc:`/topics/db/sql` for more information.
    
  1909. 
    
  1910. .. warning::
    
  1911. 
    
  1912.   ``raw()`` always triggers a new query and doesn't account for previous
    
  1913.   filtering. As such, it should generally be called from the ``Manager`` or
    
  1914.   from a fresh ``QuerySet`` instance.
    
  1915. 
    
  1916. Operators that return new ``QuerySet``\s
    
  1917. ----------------------------------------
    
  1918. 
    
  1919. Combined querysets must use the same model.
    
  1920. 
    
  1921. AND (``&``)
    
  1922. ~~~~~~~~~~~
    
  1923. 
    
  1924. Combines two ``QuerySet``\s using the SQL ``AND`` operator.
    
  1925. 
    
  1926. The following are equivalent::
    
  1927. 
    
  1928.     Model.objects.filter(x=1) & Model.objects.filter(y=2)
    
  1929.     Model.objects.filter(x=1, y=2)
    
  1930.     from django.db.models import Q
    
  1931.     Model.objects.filter(Q(x=1) & Q(y=2))
    
  1932. 
    
  1933. SQL equivalent:
    
  1934. 
    
  1935. .. code-block:: sql
    
  1936. 
    
  1937.     SELECT ... WHERE x=1 AND y=2
    
  1938. 
    
  1939. OR (``|``)
    
  1940. ~~~~~~~~~~
    
  1941. 
    
  1942. Combines two ``QuerySet``\s using the SQL ``OR`` operator.
    
  1943. 
    
  1944. The following are equivalent::
    
  1945. 
    
  1946.     Model.objects.filter(x=1) | Model.objects.filter(y=2)
    
  1947.     from django.db.models import Q
    
  1948.     Model.objects.filter(Q(x=1) | Q(y=2))
    
  1949. 
    
  1950. SQL equivalent:
    
  1951. 
    
  1952. .. code-block:: sql
    
  1953. 
    
  1954.     SELECT ... WHERE x=1 OR y=2
    
  1955. 
    
  1956. ``|`` is not a commutative operation, as different (though equivalent) queries
    
  1957. may be generated.
    
  1958. 
    
  1959. XOR (``^``)
    
  1960. ~~~~~~~~~~~
    
  1961. 
    
  1962. .. versionadded:: 4.1
    
  1963. 
    
  1964. Combines two ``QuerySet``\s using the SQL ``XOR`` operator.
    
  1965. 
    
  1966. The following are equivalent::
    
  1967. 
    
  1968.     Model.objects.filter(x=1) ^ Model.objects.filter(y=2)
    
  1969.     from django.db.models import Q
    
  1970.     Model.objects.filter(Q(x=1) ^ Q(y=2))
    
  1971. 
    
  1972. SQL equivalent:
    
  1973. 
    
  1974. .. code-block:: sql
    
  1975. 
    
  1976.     SELECT ... WHERE x=1 XOR y=2
    
  1977. 
    
  1978. .. note::
    
  1979. 
    
  1980.     ``XOR`` is natively supported on MariaDB and MySQL. On other databases,
    
  1981.     ``x ^ y ^ ... ^ z`` is converted to an equivalent:
    
  1982. 
    
  1983.     .. code-block:: sql
    
  1984. 
    
  1985.         (x OR y OR ... OR z) AND
    
  1986.         1=(
    
  1987.             (CASE WHEN x THEN 1 ELSE 0 END) +
    
  1988.             (CASE WHEN y THEN 1 ELSE 0 END) +
    
  1989.             ...
    
  1990.             (CASE WHEN z THEN 1 ELSE 0 END) +
    
  1991.         )
    
  1992. 
    
  1993. Methods that do not return ``QuerySet``\s
    
  1994. -----------------------------------------
    
  1995. 
    
  1996. The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
    
  1997. something *other than* a ``QuerySet``.
    
  1998. 
    
  1999. These methods do not use a cache (see :ref:`caching-and-querysets`). Rather,
    
  2000. they query the database each time they're called.
    
  2001. 
    
  2002. Because these methods evaluate the QuerySet, they are blocking calls, and so
    
  2003. their main (synchronous) versions cannot be called from asynchronous code. For
    
  2004. this reason, each has a corresponding asynchronous version with an ``a`` prefix
    
  2005. - for example, rather than ``get(…)`` you can ``await aget(…)``.
    
  2006. 
    
  2007. There is usually no difference in behavior apart from their asynchronous
    
  2008. nature, but any differences are noted below next to each method.
    
  2009. 
    
  2010. .. versionchanged:: 4.1
    
  2011. 
    
  2012.     The asynchronous versions of each method, prefixed with ``a`` was added.
    
  2013. 
    
  2014. ``get()``
    
  2015. ~~~~~~~~~
    
  2016. 
    
  2017. .. method:: get(*args, **kwargs)
    
  2018. .. method:: aget(*args, **kwargs)
    
  2019. 
    
  2020. *Asynchronous version*: ``aget()``
    
  2021. 
    
  2022. Returns the object matching the given lookup parameters, which should be in
    
  2023. the format described in `Field lookups`_. You should use lookups that are
    
  2024. guaranteed unique, such as the primary key or fields in a unique constraint.
    
  2025. For example::
    
  2026. 
    
  2027.     Entry.objects.get(id=1)
    
  2028.     Entry.objects.get(Q(blog=blog) & Q(entry_number=1))
    
  2029. 
    
  2030. If you expect a queryset to already return one row, you can use ``get()``
    
  2031. without any arguments to return the object for that row::
    
  2032. 
    
  2033.     Entry.objects.filter(pk=1).get()
    
  2034. 
    
  2035. If ``get()`` doesn't find any object, it raises a :exc:`Model.DoesNotExist
    
  2036. <django.db.models.Model.DoesNotExist>` exception::
    
  2037. 
    
  2038.     Entry.objects.get(id=-999) # raises Entry.DoesNotExist
    
  2039. 
    
  2040. If ``get()`` finds more than one object, it raises a
    
  2041. :exc:`Model.MultipleObjectsReturned
    
  2042. <django.db.models.Model.MultipleObjectsReturned>` exception::
    
  2043. 
    
  2044.     Entry.objects.get(name='A Duplicated Name') # raises Entry.MultipleObjectsReturned
    
  2045. 
    
  2046. Both these exception classes are attributes of the model class, and specific to
    
  2047. that model. If you want to handle such exceptions from several ``get()`` calls
    
  2048. for different models, you can use their generic base classes. For example, you
    
  2049. can use :exc:`django.core.exceptions.ObjectDoesNotExist`  to handle
    
  2050. :exc:`~django.db.models.Model.DoesNotExist` exceptions from multiple models::
    
  2051. 
    
  2052.     from django.core.exceptions import ObjectDoesNotExist
    
  2053. 
    
  2054.     try:
    
  2055.         blog = Blog.objects.get(id=1)
    
  2056.         entry = Entry.objects.get(blog=blog, entry_number=1)
    
  2057.     except ObjectDoesNotExist:
    
  2058.         print("Either the blog or entry doesn't exist.")
    
  2059. 
    
  2060. .. versionchanged:: 4.1
    
  2061. 
    
  2062.     ``aget()`` method was added.
    
  2063. 
    
  2064. ``create()``
    
  2065. ~~~~~~~~~~~~
    
  2066. 
    
  2067. .. method:: create(**kwargs)
    
  2068. .. method:: acreate(*args, **kwargs)
    
  2069. 
    
  2070. *Asynchronous version*: ``acreate()``
    
  2071. 
    
  2072. A convenience method for creating an object and saving it all in one step.  Thus::
    
  2073. 
    
  2074.     p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
    
  2075. 
    
  2076. and::
    
  2077. 
    
  2078.     p = Person(first_name="Bruce", last_name="Springsteen")
    
  2079.     p.save(force_insert=True)
    
  2080. 
    
  2081. are equivalent.
    
  2082. 
    
  2083. The :ref:`force_insert <ref-models-force-insert>` parameter is documented
    
  2084. elsewhere, but all it means is that a new object will always be created.
    
  2085. Normally you won't need to worry about this. However, if your model contains a
    
  2086. manual primary key value that you set and if that value already exists in the
    
  2087. database, a call to ``create()`` will fail with an
    
  2088. :exc:`~django.db.IntegrityError` since primary keys must be unique. Be
    
  2089. prepared to handle the exception if you are using manual primary keys.
    
  2090. 
    
  2091. .. versionchanged:: 4.1
    
  2092. 
    
  2093.     ``acreate()`` method was added.
    
  2094. 
    
  2095. ``get_or_create()``
    
  2096. ~~~~~~~~~~~~~~~~~~~
    
  2097. 
    
  2098. .. method:: get_or_create(defaults=None, **kwargs)
    
  2099. .. method:: aget_or_create(defaults=None, **kwargs)
    
  2100. 
    
  2101. *Asynchronous version*: ``aget_or_create()``
    
  2102. 
    
  2103. A convenience method for looking up an object with the given ``kwargs`` (may be
    
  2104. empty if your model has defaults for all fields), creating one if necessary.
    
  2105. 
    
  2106. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
    
  2107. created object and ``created`` is a boolean specifying whether a new object was
    
  2108. created.
    
  2109. 
    
  2110. This is meant to prevent duplicate objects from being created when requests are
    
  2111. made in parallel, and as a shortcut to boilerplatish code. For example::
    
  2112. 
    
  2113.     try:
    
  2114.         obj = Person.objects.get(first_name='John', last_name='Lennon')
    
  2115.     except Person.DoesNotExist:
    
  2116.         obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
    
  2117.         obj.save()
    
  2118. 
    
  2119. Here, with concurrent requests, multiple attempts to save a ``Person`` with
    
  2120. the same parameters may be made. To avoid this race condition, the above
    
  2121. example can be rewritten using ``get_or_create()`` like so::
    
  2122. 
    
  2123.     obj, created = Person.objects.get_or_create(
    
  2124.         first_name='John',
    
  2125.         last_name='Lennon',
    
  2126.         defaults={'birthday': date(1940, 10, 9)},
    
  2127.     )
    
  2128. 
    
  2129. Any keyword arguments passed to ``get_or_create()`` — *except* an optional one
    
  2130. called ``defaults`` — will be used in a :meth:`get()` call. If an object is
    
  2131. found, ``get_or_create()`` returns a tuple of that object and ``False``.
    
  2132. 
    
  2133. .. warning::
    
  2134. 
    
  2135.     This method is atomic assuming that the database enforces uniqueness of the
    
  2136.     keyword arguments (see :attr:`~django.db.models.Field.unique` or
    
  2137.     :attr:`~django.db.models.Options.unique_together`). If the fields used in the
    
  2138.     keyword arguments do not have a uniqueness constraint, concurrent calls to
    
  2139.     this method may result in multiple rows with the same parameters being
    
  2140.     inserted.
    
  2141. 
    
  2142. You can specify more complex conditions for the retrieved object by chaining
    
  2143. ``get_or_create()`` with ``filter()`` and using :class:`Q objects
    
  2144. <django.db.models.Q>`. For example, to retrieve Robert or Bob Marley if either
    
  2145. exists, and create the latter otherwise::
    
  2146. 
    
  2147.     from django.db.models import Q
    
  2148. 
    
  2149.     obj, created = Person.objects.filter(
    
  2150.         Q(first_name='Bob') | Q(first_name='Robert'),
    
  2151.     ).get_or_create(last_name='Marley', defaults={'first_name': 'Bob'})
    
  2152. 
    
  2153. If multiple objects are found, ``get_or_create()`` raises
    
  2154. :exc:`~django.core.exceptions.MultipleObjectsReturned`. If an object is *not*
    
  2155. found, ``get_or_create()`` will instantiate and save a new object, returning a
    
  2156. tuple of the new object and ``True``. The new object will be created roughly
    
  2157. according to this algorithm::
    
  2158. 
    
  2159.     params = {k: v for k, v in kwargs.items() if '__' not in k}
    
  2160.     params.update({k: v() if callable(v) else v for k, v in defaults.items()})
    
  2161.     obj = self.model(**params)
    
  2162.     obj.save()
    
  2163. 
    
  2164. In English, that means start with any non-``'defaults'`` keyword argument that
    
  2165. doesn't contain a double underscore (which would indicate a non-exact lookup).
    
  2166. Then add the contents of ``defaults``, overriding any keys if necessary, and
    
  2167. use the result as the keyword arguments to the model class. If there are any
    
  2168. callables in ``defaults``, evaluate them. As hinted at above, this is a
    
  2169. simplification of the algorithm that is used, but it contains all the pertinent
    
  2170. details. The internal implementation has some more error-checking than this and
    
  2171. handles some extra edge-conditions; if you're interested, read the code.
    
  2172. 
    
  2173. If you have a field named ``defaults`` and want to use it as an exact lookup in
    
  2174. ``get_or_create()``, use ``'defaults__exact'``, like so::
    
  2175. 
    
  2176.     Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
    
  2177. 
    
  2178. The ``get_or_create()`` method has similar error behavior to :meth:`create()`
    
  2179. when you're using manually specified primary keys. If an object needs to be
    
  2180. created and the key already exists in the database, an
    
  2181. :exc:`~django.db.IntegrityError` will be raised.
    
  2182. 
    
  2183. Finally, a word on using ``get_or_create()`` in Django views. Please make sure
    
  2184. to use it only in ``POST`` requests unless you have a good reason not to.
    
  2185. ``GET`` requests shouldn't have any effect on data. Instead, use ``POST``
    
  2186. whenever a request to a page has a side effect on your data. For more, see
    
  2187. :rfc:`Safe methods <7231#section-4.2.1>` in the HTTP spec.
    
  2188. 
    
  2189. .. warning::
    
  2190. 
    
  2191.   You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`
    
  2192.   attributes and reverse relations. In that case you will restrict the queries
    
  2193.   inside the context of that relation. That could lead you to some integrity
    
  2194.   problems if you don't use it consistently.
    
  2195. 
    
  2196.   Being the following models::
    
  2197. 
    
  2198.       class Chapter(models.Model):
    
  2199.           title = models.CharField(max_length=255, unique=True)
    
  2200. 
    
  2201.       class Book(models.Model):
    
  2202.           title = models.CharField(max_length=256)
    
  2203.           chapters = models.ManyToManyField(Chapter)
    
  2204. 
    
  2205.   You can use ``get_or_create()`` through Book's chapters field, but it only
    
  2206.   fetches inside the context of that book::
    
  2207. 
    
  2208.       >>> book = Book.objects.create(title="Ulysses")
    
  2209.       >>> book.chapters.get_or_create(title="Telemachus")
    
  2210.       (<Chapter: Telemachus>, True)
    
  2211.       >>> book.chapters.get_or_create(title="Telemachus")
    
  2212.       (<Chapter: Telemachus>, False)
    
  2213.       >>> Chapter.objects.create(title="Chapter 1")
    
  2214.       <Chapter: Chapter 1>
    
  2215.       >>> book.chapters.get_or_create(title="Chapter 1")
    
  2216.       # Raises IntegrityError
    
  2217. 
    
  2218.   This is happening because it's trying to get or create "Chapter 1" through the
    
  2219.   book "Ulysses", but it can't do any of them: the relation can't fetch that
    
  2220.   chapter because it isn't related to that book, but it can't create it either
    
  2221.   because ``title`` field should be unique.
    
  2222. 
    
  2223. .. versionchanged:: 4.1
    
  2224. 
    
  2225.     ``aget_or_create()`` method was added.
    
  2226. 
    
  2227. ``update_or_create()``
    
  2228. ~~~~~~~~~~~~~~~~~~~~~~
    
  2229. 
    
  2230. .. method:: update_or_create(defaults=None, **kwargs)
    
  2231. .. method:: aupdate_or_create(defaults=None, **kwargs)
    
  2232. 
    
  2233. *Asynchronous version*: ``aupdate_or_create()``
    
  2234. 
    
  2235. A convenience method for updating an object with the given ``kwargs``, creating
    
  2236. a new one if necessary. The ``defaults`` is a dictionary of (field, value)
    
  2237. pairs used to update the object. The values in ``defaults`` can be callables.
    
  2238. 
    
  2239. Returns a tuple of ``(object, created)``, where ``object`` is the created or
    
  2240. updated object and ``created`` is a boolean specifying whether a new object was
    
  2241. created.
    
  2242. 
    
  2243. The ``update_or_create`` method tries to fetch an object from database based on
    
  2244. the given ``kwargs``. If a match is found, it updates the fields passed in the
    
  2245. ``defaults`` dictionary.
    
  2246. 
    
  2247. This is meant as a shortcut to boilerplatish code. For example::
    
  2248. 
    
  2249.     defaults = {'first_name': 'Bob'}
    
  2250.     try:
    
  2251.         obj = Person.objects.get(first_name='John', last_name='Lennon')
    
  2252.         for key, value in defaults.items():
    
  2253.             setattr(obj, key, value)
    
  2254.         obj.save()
    
  2255.     except Person.DoesNotExist:
    
  2256.         new_values = {'first_name': 'John', 'last_name': 'Lennon'}
    
  2257.         new_values.update(defaults)
    
  2258.         obj = Person(**new_values)
    
  2259.         obj.save()
    
  2260. 
    
  2261. This pattern gets quite unwieldy as the number of fields in a model goes up.
    
  2262. The above example can be rewritten using ``update_or_create()`` like so::
    
  2263. 
    
  2264.     obj, created = Person.objects.update_or_create(
    
  2265.         first_name='John', last_name='Lennon',
    
  2266.         defaults={'first_name': 'Bob'},
    
  2267.     )
    
  2268. 
    
  2269. For a detailed description of how names passed in ``kwargs`` are resolved, see
    
  2270. :meth:`get_or_create`.
    
  2271. 
    
  2272. As described above in :meth:`get_or_create`, this method is prone to a
    
  2273. race-condition which can result in multiple rows being inserted simultaneously
    
  2274. if uniqueness is not enforced at the database level.
    
  2275. 
    
  2276. Like :meth:`get_or_create` and :meth:`create`, if you're using manually
    
  2277. specified primary keys and an object needs to be created but the key already
    
  2278. exists in the database, an :exc:`~django.db.IntegrityError` is raised.
    
  2279. 
    
  2280. .. versionchanged:: 4.1
    
  2281. 
    
  2282.     ``aupdate_or_create()`` method was added.
    
  2283. 
    
  2284. ``bulk_create()``
    
  2285. ~~~~~~~~~~~~~~~~~
    
  2286. 
    
  2287. .. method:: bulk_create(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None)
    
  2288. .. method:: abulk_create(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None)
    
  2289. 
    
  2290. *Asynchronous version*: ``abulk_create()``
    
  2291. 
    
  2292. This method inserts the provided list of objects into the database in an
    
  2293. efficient manner (generally only 1 query, no matter how many objects there
    
  2294. are), and returns created objects as a list, in the same order as provided::
    
  2295. 
    
  2296.     >>> objs = Entry.objects.bulk_create([
    
  2297.     ...     Entry(headline='This is a test'),
    
  2298.     ...     Entry(headline='This is only a test'),
    
  2299.     ... ])
    
  2300. 
    
  2301. This has a number of caveats though:
    
  2302. 
    
  2303. * The model's ``save()`` method will not be called, and the ``pre_save`` and
    
  2304.   ``post_save`` signals will not be sent.
    
  2305. * It does not work with child models in a multi-table inheritance scenario.
    
  2306. * If the model's primary key is an :class:`~django.db.models.AutoField`, the
    
  2307.   primary key attribute can only be retrieved on certain databases (currently
    
  2308.   PostgreSQL, MariaDB 10.5+, and SQLite 3.35+). On other databases, it will not
    
  2309.   be set.
    
  2310. * It does not work with many-to-many relationships.
    
  2311. * It casts ``objs`` to a list, which fully evaluates ``objs`` if it's a
    
  2312.   generator. The cast allows inspecting all objects so that any objects with a
    
  2313.   manually set primary key can be inserted first. If you want to insert objects
    
  2314.   in batches without evaluating the entire generator at once, you can use this
    
  2315.   technique as long as the objects don't have any manually set primary keys::
    
  2316. 
    
  2317.     from itertools import islice
    
  2318. 
    
  2319.     batch_size = 100
    
  2320.     objs = (Entry(headline='Test %s' % i) for i in range(1000))
    
  2321.     while True:
    
  2322.         batch = list(islice(objs, batch_size))
    
  2323.         if not batch:
    
  2324.             break
    
  2325.         Entry.objects.bulk_create(batch, batch_size)
    
  2326. 
    
  2327. The ``batch_size`` parameter controls how many objects are created in a single
    
  2328. query. The default is to create all objects in one batch, except for SQLite
    
  2329. where the default is such that at most 999 variables per query are used.
    
  2330. 
    
  2331. On databases that support it (all but Oracle), setting the ``ignore_conflicts``
    
  2332. parameter to ``True`` tells the database to ignore failure to insert any rows
    
  2333. that fail constraints such as duplicate unique values.
    
  2334. 
    
  2335. On databases that support it (all except Oracle and SQLite < 3.24), setting the
    
  2336. ``update_conflicts`` parameter to ``True``, tells the database to update
    
  2337. ``update_fields`` when a row insertion fails on conflicts. On PostgreSQL and
    
  2338. SQLite, in addition to ``update_fields``, a list of ``unique_fields`` that may
    
  2339. be in conflict must be provided.
    
  2340. 
    
  2341. Enabling the ``ignore_conflicts`` or ``update_conflicts`` parameter disable
    
  2342. setting the primary key on each model instance (if the database normally
    
  2343. support it).
    
  2344. 
    
  2345. .. warning::
    
  2346. 
    
  2347.     On MySQL and MariaDB, setting the ``ignore_conflicts`` parameter to
    
  2348.     ``True`` turns certain types of errors, other than duplicate key, into
    
  2349.     warnings. Even with Strict Mode. For example: invalid values or
    
  2350.     non-nullable violations. See the `MySQL documentation`_ and
    
  2351.     `MariaDB documentation`_ for more details.
    
  2352. 
    
  2353. .. _MySQL documentation: https://dev.mysql.com/doc/refman/en/sql-mode.html#ignore-strict-comparison
    
  2354. .. _MariaDB documentation: https://mariadb.com/kb/en/ignore/
    
  2355. 
    
  2356. .. versionchanged:: 4.0
    
  2357. 
    
  2358.     Support for the fetching primary key attributes on SQLite 3.35+ was added.
    
  2359. 
    
  2360. .. versionchanged:: 4.1
    
  2361. 
    
  2362.     The ``update_conflicts``, ``update_fields``, and ``unique_fields``
    
  2363.     parameters were added to support updating fields when a row insertion fails
    
  2364.     on conflict.
    
  2365. 
    
  2366.     ``abulk_create()`` method was added.
    
  2367. 
    
  2368. ``bulk_update()``
    
  2369. ~~~~~~~~~~~~~~~~~
    
  2370. 
    
  2371. .. method:: bulk_update(objs, fields, batch_size=None)
    
  2372. .. method:: abulk_update(objs, fields, batch_size=None)
    
  2373. 
    
  2374. *Asynchronous version*: ``abulk_update()``
    
  2375. 
    
  2376. This method efficiently updates the given fields on the provided model
    
  2377. instances, generally with one query, and returns the number of objects
    
  2378. updated::
    
  2379. 
    
  2380.     >>> objs = [
    
  2381.     ...    Entry.objects.create(headline='Entry 1'),
    
  2382.     ...    Entry.objects.create(headline='Entry 2'),
    
  2383.     ... ]
    
  2384.     >>> objs[0].headline = 'This is entry 1'
    
  2385.     >>> objs[1].headline = 'This is entry 2'
    
  2386.     >>> Entry.objects.bulk_update(objs, ['headline'])
    
  2387.     2
    
  2388. 
    
  2389. .. versionchanged:: 4.0
    
  2390. 
    
  2391.     The return value of the number of objects updated was added.
    
  2392. 
    
  2393. :meth:`.QuerySet.update` is used to save the changes, so this is more efficient
    
  2394. than iterating through the list of models and calling ``save()`` on each of
    
  2395. them, but it has a few caveats:
    
  2396. 
    
  2397. * You cannot update the model's primary key.
    
  2398. * Each model's ``save()`` method isn't called, and the
    
  2399.   :attr:`~django.db.models.signals.pre_save` and
    
  2400.   :attr:`~django.db.models.signals.post_save` signals aren't sent.
    
  2401. * If updating a large number of columns in a large number of rows, the SQL
    
  2402.   generated can be very large. Avoid this by specifying a suitable
    
  2403.   ``batch_size``.
    
  2404. * Updating fields defined on multi-table inheritance ancestors will incur an
    
  2405.   extra query per ancestor.
    
  2406. * When an individual batch contains duplicates, only the first instance in that
    
  2407.   batch will result in an update.
    
  2408. * The number of objects updated returned by the function may be fewer than the
    
  2409.   number of objects passed in. This can be due to duplicate objects passed in
    
  2410.   which are updated in the same batch or race conditions such that objects are
    
  2411.   no longer present in the database.
    
  2412. 
    
  2413. The ``batch_size`` parameter controls how many objects are saved in a single
    
  2414. query. The default is to update all objects in one batch, except for SQLite
    
  2415. and Oracle which have restrictions on the number of variables used in a query.
    
  2416. 
    
  2417. .. versionchanged:: 4.1
    
  2418. 
    
  2419.     ``abulk_update()`` method was added.
    
  2420. 
    
  2421. ``count()``
    
  2422. ~~~~~~~~~~~
    
  2423. 
    
  2424. .. method:: count()
    
  2425. .. method:: acount()
    
  2426. 
    
  2427. *Asynchronous version*: ``acount()``
    
  2428. 
    
  2429. Returns an integer representing the number of objects in the database matching
    
  2430. the ``QuerySet``.
    
  2431. 
    
  2432. Example::
    
  2433. 
    
  2434.     # Returns the total number of entries in the database.
    
  2435.     Entry.objects.count()
    
  2436. 
    
  2437.     # Returns the number of entries whose headline contains 'Lennon'
    
  2438.     Entry.objects.filter(headline__contains='Lennon').count()
    
  2439. 
    
  2440. A ``count()`` call performs a ``SELECT COUNT(*)`` behind the scenes, so you
    
  2441. should always use ``count()`` rather than loading all of the record into Python
    
  2442. objects and calling ``len()`` on the result (unless you need to load the
    
  2443. objects into memory anyway, in which case ``len()`` will be faster).
    
  2444. 
    
  2445. Note that if you want the number of items in a ``QuerySet`` and are also
    
  2446. retrieving model instances from it (for example, by iterating over it), it's
    
  2447. probably more efficient to use ``len(queryset)`` which won't cause an extra
    
  2448. database query like ``count()`` would.
    
  2449. 
    
  2450. If the queryset has already been fully retrieved, ``count()`` will use that
    
  2451. length rather than perform an extra database query.
    
  2452. 
    
  2453. .. versionchanged:: 4.1
    
  2454. 
    
  2455.     ``acount()`` method was added.
    
  2456. 
    
  2457. ``in_bulk()``
    
  2458. ~~~~~~~~~~~~~
    
  2459. 
    
  2460. .. method:: in_bulk(id_list=None, *, field_name='pk')
    
  2461. .. method:: ain_bulk(id_list=None, *, field_name='pk')
    
  2462. 
    
  2463. *Asynchronous version*: ``ain_bulk()``
    
  2464. 
    
  2465. Takes a list of field values (``id_list``) and the ``field_name`` for those
    
  2466. values, and returns a dictionary mapping each value to an instance of the
    
  2467. object with the given field value. No
    
  2468. :exc:`django.core.exceptions.ObjectDoesNotExist` exceptions will ever be raised
    
  2469. by ``in_bulk``; that is, any ``id_list`` value not matching any instance will
    
  2470. simply be ignored. If ``id_list`` isn't provided, all objects
    
  2471. in the queryset are returned. ``field_name`` must be a unique field or a
    
  2472. distinct field (if there's only one field specified in :meth:`distinct`).
    
  2473. ``field_name`` defaults to the primary key.
    
  2474. 
    
  2475. Example::
    
  2476. 
    
  2477.     >>> Blog.objects.in_bulk([1])
    
  2478.     {1: <Blog: Beatles Blog>}
    
  2479.     >>> Blog.objects.in_bulk([1, 2])
    
  2480.     {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
    
  2481.     >>> Blog.objects.in_bulk([])
    
  2482.     {}
    
  2483.     >>> Blog.objects.in_bulk()
    
  2484.     {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}
    
  2485.     >>> Blog.objects.in_bulk(['beatles_blog'], field_name='slug')
    
  2486.     {'beatles_blog': <Blog: Beatles Blog>}
    
  2487.     >>> Blog.objects.distinct('name').in_bulk(field_name='name')
    
  2488.     {'Beatles Blog': <Blog: Beatles Blog>, 'Cheddar Talk': <Blog: Cheddar Talk>, 'Django Weblog': <Blog: Django Weblog>}
    
  2489. 
    
  2490. If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
    
  2491. 
    
  2492. .. versionchanged:: 4.1
    
  2493. 
    
  2494.     ``ain_bulk()`` method was added.
    
  2495. 
    
  2496. ``iterator()``
    
  2497. ~~~~~~~~~~~~~~
    
  2498. 
    
  2499. .. method:: iterator(chunk_size=None)
    
  2500. .. method:: aiterator(chunk_size=None)
    
  2501. 
    
  2502. *Asynchronous version*: ``aiterator()``
    
  2503. 
    
  2504. Evaluates the ``QuerySet`` (by performing the query) and returns an iterator
    
  2505. (see :pep:`234`) over the results, or an asynchronous iterator (see :pep:`492`)
    
  2506. if you call its asynchronous version ``aiterator``.
    
  2507. 
    
  2508. A ``QuerySet`` typically caches its results internally so that repeated
    
  2509. evaluations do not result in additional queries. In contrast, ``iterator()``
    
  2510. will read results directly, without doing any caching at the ``QuerySet`` level
    
  2511. (internally, the default iterator calls ``iterator()`` and caches the return
    
  2512. value). For a ``QuerySet`` which returns a large number of objects that you
    
  2513. only need to access once, this can result in better performance and a
    
  2514. significant reduction in memory.
    
  2515. 
    
  2516. Note that using ``iterator()`` on a ``QuerySet`` which has already been
    
  2517. evaluated will force it to evaluate again, repeating the query.
    
  2518. 
    
  2519. ``iterator()`` is compatible with previous calls to ``prefetch_related()`` as
    
  2520. long as ``chunk_size`` is given. Larger values will necessitate fewer queries
    
  2521. to accomplish the prefetching at the cost of greater memory usage.
    
  2522. 
    
  2523. .. note::
    
  2524. 
    
  2525.     ``aiterator()`` is *not* compatible with previous calls to
    
  2526.     ``prefetch_related()``.
    
  2527. 
    
  2528. On some databases (e.g. Oracle, `SQLite
    
  2529. <https://www.sqlite.org/limits.html#max_variable_number>`_), the maximum number
    
  2530. of terms in an SQL ``IN`` clause might be limited. Hence values below this
    
  2531. limit should be used. (In particular, when prefetching across two or more
    
  2532. relations, a ``chunk_size`` should be small enough that the anticipated number
    
  2533. of results for each prefetched relation still falls below the limit.)
    
  2534. 
    
  2535. So long as the QuerySet does not prefetch any related objects, providing no
    
  2536. value for ``chunk_size`` will result in Django using an implicit default of
    
  2537. 2000.
    
  2538. 
    
  2539. Depending on the database backend, query results will either be loaded all at
    
  2540. once or streamed from the database using server-side cursors.
    
  2541. 
    
  2542. .. versionchanged:: 4.1
    
  2543. 
    
  2544.     Support for prefetching related objects was added to ``iterator()``.
    
  2545. 
    
  2546.     ``aiterator()`` method was added.
    
  2547. 
    
  2548. .. deprecated:: 4.1
    
  2549. 
    
  2550.     Using ``iterator()`` on a queryset that prefetches related objects without
    
  2551.     providing the ``chunk_size`` is deprecated. In Django 5.0, an exception
    
  2552.     will be raise.
    
  2553. 
    
  2554. With server-side cursors
    
  2555. ^^^^^^^^^^^^^^^^^^^^^^^^
    
  2556. 
    
  2557. Oracle and :ref:`PostgreSQL <postgresql-server-side-cursors>` use server-side
    
  2558. cursors to stream results from the database without loading the entire result
    
  2559. set into memory.
    
  2560. 
    
  2561. The Oracle database driver always uses server-side cursors.
    
  2562. 
    
  2563. With server-side cursors, the ``chunk_size`` parameter specifies the number of
    
  2564. results to cache at the database driver level. Fetching bigger chunks
    
  2565. diminishes the number of round trips between the database driver and the
    
  2566. database, at the expense of memory.
    
  2567. 
    
  2568. On PostgreSQL, server-side cursors will only be used when the
    
  2569. :setting:`DISABLE_SERVER_SIDE_CURSORS <DATABASE-DISABLE_SERVER_SIDE_CURSORS>`
    
  2570. setting is ``False``. Read :ref:`transaction-pooling-server-side-cursors` if
    
  2571. you're using a connection pooler configured in transaction pooling mode. When
    
  2572. server-side cursors are disabled, the behavior is the same as databases that
    
  2573. don't support server-side cursors.
    
  2574. 
    
  2575. Without server-side cursors
    
  2576. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
  2577. 
    
  2578. MySQL doesn't support streaming results, hence the Python database driver loads
    
  2579. the entire result set into memory. The result set is then transformed into
    
  2580. Python row objects by the database adapter using the ``fetchmany()`` method
    
  2581. defined in :pep:`249`.
    
  2582. 
    
  2583. SQLite can fetch results in batches using ``fetchmany()``, but since SQLite
    
  2584. doesn't provide isolation between queries within a connection, be careful when
    
  2585. writing to the table being iterated over. See :ref:`sqlite-isolation` for
    
  2586. more information.
    
  2587. 
    
  2588. The ``chunk_size`` parameter controls the size of batches Django retrieves from
    
  2589. the database driver. Larger batches decrease the overhead of communicating with
    
  2590. the database driver at the expense of a slight increase in memory consumption.
    
  2591. 
    
  2592. So long as the QuerySet does not prefetch any related objects, providing no
    
  2593. value for ``chunk_size`` will result in Django using an implicit default of
    
  2594. 2000, a value derived from `a calculation on the psycopg mailing list
    
  2595. <https://www.postgresql.org/message-id/4D2F2C71.8080805%40dndg.it>`_:
    
  2596. 
    
  2597.     Assuming rows of 10-20 columns with a mix of textual and numeric data, 2000
    
  2598.     is going to fetch less than 100KB of data, which seems a good compromise
    
  2599.     between the number of rows transferred and the data discarded if the loop
    
  2600.     is exited early.
    
  2601. 
    
  2602. ``latest()``
    
  2603. ~~~~~~~~~~~~
    
  2604. 
    
  2605. .. method:: latest(*fields)
    
  2606. .. method:: alatest(*fields)
    
  2607. 
    
  2608. *Asynchronous version*: ``alatest()``
    
  2609. 
    
  2610. Returns the latest object in the table based on the given field(s).
    
  2611. 
    
  2612. This example returns the latest ``Entry`` in the table, according to the
    
  2613. ``pub_date`` field::
    
  2614. 
    
  2615.     Entry.objects.latest('pub_date')
    
  2616. 
    
  2617. You can also choose the latest based on several fields. For example, to select
    
  2618. the ``Entry`` with the earliest ``expire_date`` when two entries have the same
    
  2619. ``pub_date``::
    
  2620. 
    
  2621.     Entry.objects.latest('pub_date', '-expire_date')
    
  2622. 
    
  2623. The negative sign in ``'-expire_date'`` means to sort ``expire_date`` in
    
  2624. *descending* order. Since ``latest()`` gets the last result, the ``Entry`` with
    
  2625. the earliest ``expire_date`` is selected.
    
  2626. 
    
  2627. If your model's :ref:`Meta <meta-options>` specifies
    
  2628. :attr:`~django.db.models.Options.get_latest_by`, you can omit any arguments to
    
  2629. ``earliest()`` or ``latest()``. The fields specified in
    
  2630. :attr:`~django.db.models.Options.get_latest_by` will be used by default.
    
  2631. 
    
  2632. Like :meth:`get()`, ``earliest()`` and ``latest()`` raise
    
  2633. :exc:`~django.db.models.Model.DoesNotExist` if there is no object with the
    
  2634. given parameters.
    
  2635. 
    
  2636. Note that ``earliest()`` and ``latest()`` exist purely for convenience and
    
  2637. readability.
    
  2638. 
    
  2639. .. admonition:: ``earliest()`` and ``latest()`` may return instances with null dates.
    
  2640. 
    
  2641.     Since ordering is delegated to the database, results on fields that allow
    
  2642.     null values may be ordered differently if you use different databases. For
    
  2643.     example, PostgreSQL and MySQL sort null values as if they are higher than
    
  2644.     non-null values, while SQLite does the opposite.
    
  2645. 
    
  2646.     You may want to filter out null values::
    
  2647. 
    
  2648.         Entry.objects.filter(pub_date__isnull=False).latest('pub_date')
    
  2649. 
    
  2650. .. versionchanged:: 4.1
    
  2651. 
    
  2652.     ``alatest()`` method was added.
    
  2653. 
    
  2654. ``earliest()``
    
  2655. ~~~~~~~~~~~~~~
    
  2656. 
    
  2657. .. method:: earliest(*fields)
    
  2658. .. method:: aearliest(*fields)
    
  2659. 
    
  2660. *Asynchronous version*: ``aearliest()``
    
  2661. 
    
  2662. Works otherwise like :meth:`~django.db.models.query.QuerySet.latest` except
    
  2663. the direction is changed.
    
  2664. 
    
  2665. .. versionchanged:: 4.1
    
  2666. 
    
  2667.     ``aearliest()`` method was added.
    
  2668. 
    
  2669. ``first()``
    
  2670. ~~~~~~~~~~~
    
  2671. 
    
  2672. .. method:: first()
    
  2673. .. method:: afirst()
    
  2674. 
    
  2675. *Asynchronous version*: ``afirst()``
    
  2676. 
    
  2677. Returns the first object matched by the queryset, or ``None`` if there
    
  2678. is no matching object. If the ``QuerySet`` has no ordering defined, then the
    
  2679. queryset is automatically ordered by the primary key. This can affect
    
  2680. aggregation results as described in :ref:`aggregation-ordering-interaction`.
    
  2681. 
    
  2682. Example::
    
  2683. 
    
  2684.     p = Article.objects.order_by('title', 'pub_date').first()
    
  2685. 
    
  2686. Note that ``first()`` is a convenience method, the following code sample is
    
  2687. equivalent to the above example::
    
  2688. 
    
  2689.     try:
    
  2690.         p = Article.objects.order_by('title', 'pub_date')[0]
    
  2691.     except IndexError:
    
  2692.         p = None
    
  2693. 
    
  2694. .. versionchanged:: 4.1
    
  2695. 
    
  2696.     ``afirst()`` method was added.
    
  2697. 
    
  2698. ``last()``
    
  2699. ~~~~~~~~~~
    
  2700. 
    
  2701. .. method:: last()
    
  2702. .. method:: alast()
    
  2703. 
    
  2704. *Asynchronous version*: ``alast()``
    
  2705. 
    
  2706. Works like  :meth:`first()`, but returns the last object in the queryset.
    
  2707. 
    
  2708. .. versionchanged:: 4.1
    
  2709. 
    
  2710.     ``alast()`` method was added.
    
  2711. 
    
  2712. ``aggregate()``
    
  2713. ~~~~~~~~~~~~~~~
    
  2714. 
    
  2715. .. method:: aggregate(*args, **kwargs)
    
  2716. .. method:: aaggregate(*args, **kwargs)
    
  2717. 
    
  2718. *Asynchronous version*: ``aaggregate()``
    
  2719. 
    
  2720. Returns a dictionary of aggregate values (averages, sums, etc.) calculated over
    
  2721. the ``QuerySet``. Each argument to ``aggregate()`` specifies a value that will
    
  2722. be included in the dictionary that is returned.
    
  2723. 
    
  2724. The aggregation functions that are provided by Django are described in
    
  2725. `Aggregation Functions`_ below. Since aggregates are also :doc:`query
    
  2726. expressions </ref/models/expressions>`, you may combine aggregates with other
    
  2727. aggregates or values to create complex aggregates.
    
  2728. 
    
  2729. Aggregates specified using keyword arguments will use the keyword as the name
    
  2730. for the annotation. Anonymous arguments will have a name generated for them
    
  2731. based upon the name of the aggregate function and the model field that is being
    
  2732. aggregated. Complex aggregates cannot use anonymous arguments and must specify
    
  2733. a keyword argument as an alias.
    
  2734. 
    
  2735. For example, when you are working with blog entries, you may want to know the
    
  2736. number of authors that have contributed blog entries::
    
  2737. 
    
  2738.     >>> from django.db.models import Count
    
  2739.     >>> q = Blog.objects.aggregate(Count('entry'))
    
  2740.     {'entry__count': 16}
    
  2741. 
    
  2742. By using a keyword argument to specify the aggregate function, you can
    
  2743. control the name of the aggregation value that is returned::
    
  2744. 
    
  2745.     >>> q = Blog.objects.aggregate(number_of_entries=Count('entry'))
    
  2746.     {'number_of_entries': 16}
    
  2747. 
    
  2748. For an in-depth discussion of aggregation, see :doc:`the topic guide on
    
  2749. Aggregation </topics/db/aggregation>`.
    
  2750. 
    
  2751. .. versionchanged:: 4.1
    
  2752. 
    
  2753.     ``aaggregate()`` method was added.
    
  2754. 
    
  2755. ``exists()``
    
  2756. ~~~~~~~~~~~~
    
  2757. 
    
  2758. .. method:: exists()
    
  2759. .. method:: aexists()
    
  2760. 
    
  2761. *Asynchronous version*: ``aexists()``
    
  2762. 
    
  2763. Returns ``True`` if the :class:`.QuerySet` contains any results, and ``False``
    
  2764. if not. This tries to perform the query in the simplest and fastest way
    
  2765. possible, but it *does* execute nearly the same query as a normal
    
  2766. :class:`.QuerySet` query.
    
  2767. 
    
  2768. :meth:`~.QuerySet.exists` is useful for searches relating to the existence of
    
  2769. any objects in a :class:`.QuerySet`, particularly in the context of a large
    
  2770. :class:`.QuerySet`.
    
  2771. 
    
  2772. To find whether a queryset contains any items::
    
  2773. 
    
  2774.     if some_queryset.exists():
    
  2775.         print("There is at least one object in some_queryset")
    
  2776. 
    
  2777. Which will be faster than::
    
  2778. 
    
  2779.     if some_queryset:
    
  2780.         print("There is at least one object in some_queryset")
    
  2781. 
    
  2782. ... but not by a large degree (hence needing a large queryset for efficiency
    
  2783. gains).
    
  2784. 
    
  2785. Additionally, if a ``some_queryset`` has not yet been evaluated, but you know
    
  2786. that it will be at some point, then using ``some_queryset.exists()`` will do
    
  2787. more overall work (one query for the existence check plus an extra one to later
    
  2788. retrieve the results) than using ``bool(some_queryset)``, which retrieves the
    
  2789. results and then checks if any were returned.
    
  2790. 
    
  2791. .. versionchanged:: 4.1
    
  2792. 
    
  2793.     ``aexists()`` method was added.
    
  2794. 
    
  2795. ``contains()``
    
  2796. ~~~~~~~~~~~~~~
    
  2797. 
    
  2798. .. method:: contains(obj)
    
  2799. .. method:: acontains(obj)
    
  2800. 
    
  2801. *Asynchronous version*: ``acontains()``
    
  2802. 
    
  2803. .. versionadded:: 4.0
    
  2804. 
    
  2805. Returns ``True`` if the :class:`.QuerySet` contains ``obj``, and ``False`` if
    
  2806. not. This tries to perform the query in the simplest and fastest way possible.
    
  2807. 
    
  2808. :meth:`contains` is useful for checking an object membership in a
    
  2809. :class:`.QuerySet`, particularly in the context of a large :class:`.QuerySet`.
    
  2810. 
    
  2811. To check whether a queryset contains a specific item::
    
  2812. 
    
  2813.     if some_queryset.contains(obj):
    
  2814.         print('Entry contained in queryset')
    
  2815. 
    
  2816. This will be faster than the following which requires evaluating and iterating
    
  2817. through the entire queryset::
    
  2818. 
    
  2819.     if obj in some_queryset:
    
  2820.         print('Entry contained in queryset')
    
  2821. 
    
  2822. Like :meth:`exists`, if ``some_queryset`` has not yet been evaluated, but you
    
  2823. know that it will be at some point, then using ``some_queryset.contains(obj)``
    
  2824. will make an additional database query, generally resulting in slower overall
    
  2825. performance.
    
  2826. 
    
  2827. .. versionchanged:: 4.1
    
  2828. 
    
  2829.     ``acontains()`` method was added.
    
  2830. 
    
  2831. ``update()``
    
  2832. ~~~~~~~~~~~~
    
  2833. 
    
  2834. .. method:: update(**kwargs)
    
  2835. .. method:: aupdate(**kwargs)
    
  2836. 
    
  2837. *Asynchronous version*: ``aupdate()``
    
  2838. 
    
  2839. Performs an SQL update query for the specified fields, and returns
    
  2840. the number of rows matched (which may not be equal to the number of rows
    
  2841. updated if some rows already have the new value).
    
  2842. 
    
  2843. For example, to turn comments off for all blog entries published in 2010,
    
  2844. you could do this::
    
  2845. 
    
  2846.     >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
    
  2847. 
    
  2848. (This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.)
    
  2849. 
    
  2850. You can update multiple fields — there's no limit on how many. For example,
    
  2851. here we update the ``comments_on`` and ``headline`` fields::
    
  2852. 
    
  2853.     >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False, headline='This is old')
    
  2854. 
    
  2855. The ``update()`` method is applied instantly, and the only restriction on the
    
  2856. :class:`.QuerySet` that is updated is that it can only update columns in the
    
  2857. model's main table, not on related models. You can't do this, for example::
    
  2858. 
    
  2859.     >>> Entry.objects.update(blog__name='foo') # Won't work!
    
  2860. 
    
  2861. Filtering based on related fields is still possible, though::
    
  2862. 
    
  2863.     >>> Entry.objects.filter(blog__id=1).update(comments_on=True)
    
  2864. 
    
  2865. You cannot call ``update()`` on a :class:`.QuerySet` that has had a slice taken
    
  2866. or can otherwise no longer be filtered.
    
  2867. 
    
  2868. The ``update()`` method returns the number of affected rows::
    
  2869. 
    
  2870.     >>> Entry.objects.filter(id=64).update(comments_on=True)
    
  2871.     1
    
  2872. 
    
  2873.     >>> Entry.objects.filter(slug='nonexistent-slug').update(comments_on=True)
    
  2874.     0
    
  2875. 
    
  2876.     >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
    
  2877.     132
    
  2878. 
    
  2879. If you're just updating a record and don't need to do anything with the model
    
  2880. object, the most efficient approach is to call ``update()``, rather than
    
  2881. loading the model object into memory. For example, instead of doing this::
    
  2882. 
    
  2883.     e = Entry.objects.get(id=10)
    
  2884.     e.comments_on = False
    
  2885.     e.save()
    
  2886. 
    
  2887. ...do this::
    
  2888. 
    
  2889.     Entry.objects.filter(id=10).update(comments_on=False)
    
  2890. 
    
  2891. Using ``update()`` also prevents a race condition wherein something might
    
  2892. change in your database in the short period of time between loading the object
    
  2893. and calling ``save()``.
    
  2894. 
    
  2895. Finally, realize that ``update()`` does an update at the SQL level and, thus,
    
  2896. does not call any ``save()`` methods on your models, nor does it emit the
    
  2897. :attr:`~django.db.models.signals.pre_save` or
    
  2898. :attr:`~django.db.models.signals.post_save` signals (which are a consequence of
    
  2899. calling :meth:`Model.save() <django.db.models.Model.save>`). If you want to
    
  2900. update a bunch of records for a model that has a custom
    
  2901. :meth:`~django.db.models.Model.save()` method, loop over them and call
    
  2902. :meth:`~django.db.models.Model.save()`, like this::
    
  2903. 
    
  2904.     for e in Entry.objects.filter(pub_date__year=2010):
    
  2905.         e.comments_on = False
    
  2906.         e.save()
    
  2907. 
    
  2908. .. versionchanged:: 4.1
    
  2909. 
    
  2910.     ``aupdate()`` method was added.
    
  2911. 
    
  2912. Ordered queryset
    
  2913. ^^^^^^^^^^^^^^^^
    
  2914. 
    
  2915. Chaining ``order_by()`` with ``update()`` is supported only on MariaDB and
    
  2916. MySQL, and is ignored for different databases. This is useful for updating a
    
  2917. unique field in the order that is specified without conflicts. For example::
    
  2918. 
    
  2919.     Entry.objects.order_by('-number').update(number=F('number') + 1)
    
  2920. 
    
  2921. .. note::
    
  2922. 
    
  2923.     ``order_by()`` clause will be ignored if it contains annotations, inherited
    
  2924.     fields, or lookups spanning relations.
    
  2925. 
    
  2926. ``delete()``
    
  2927. ~~~~~~~~~~~~
    
  2928. 
    
  2929. .. method:: delete()
    
  2930. .. method:: adelete()
    
  2931. 
    
  2932. *Asynchronous version*: ``adelete()``
    
  2933. 
    
  2934. Performs an SQL delete query on all rows in the :class:`.QuerySet` and
    
  2935. returns the number of objects deleted and a dictionary with the number of
    
  2936. deletions per object type.
    
  2937. 
    
  2938. The ``delete()`` is applied instantly. You cannot call ``delete()`` on a
    
  2939. :class:`.QuerySet` that has had a slice taken or can otherwise no longer be
    
  2940. filtered.
    
  2941. 
    
  2942. For example, to delete all the entries in a particular blog::
    
  2943. 
    
  2944.     >>> b = Blog.objects.get(pk=1)
    
  2945. 
    
  2946.     # Delete all the entries belonging to this Blog.
    
  2947.     >>> Entry.objects.filter(blog=b).delete()
    
  2948.     (4, {'blog.Entry': 2, 'blog.Entry_authors': 2})
    
  2949. 
    
  2950. By default, Django's :class:`~django.db.models.ForeignKey` emulates the SQL
    
  2951. constraint ``ON DELETE CASCADE`` — in other words, any objects with foreign
    
  2952. keys pointing at the objects to be deleted will be deleted along with them.
    
  2953. For example::
    
  2954. 
    
  2955.     >>> blogs = Blog.objects.all()
    
  2956. 
    
  2957.     # This will delete all Blogs and all of their Entry objects.
    
  2958.     >>> blogs.delete()
    
  2959.     (5, {'blog.Blog': 1, 'blog.Entry': 2, 'blog.Entry_authors': 2})
    
  2960. 
    
  2961. This cascade behavior is customizable via the
    
  2962. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
    
  2963. :class:`~django.db.models.ForeignKey`.
    
  2964. 
    
  2965. The ``delete()`` method does a bulk delete and does not call any ``delete()``
    
  2966. methods on your models. It does, however, emit the
    
  2967. :data:`~django.db.models.signals.pre_delete` and
    
  2968. :data:`~django.db.models.signals.post_delete` signals for all deleted objects
    
  2969. (including cascaded deletions).
    
  2970. 
    
  2971. Django needs to fetch objects into memory to send signals and handle cascades.
    
  2972. However, if there are no cascades and no signals, then Django may take a
    
  2973. fast-path and delete objects without fetching into memory. For large
    
  2974. deletes this can result in significantly reduced memory usage. The amount of
    
  2975. executed queries can be reduced, too.
    
  2976. 
    
  2977. ForeignKeys which are set to :attr:`~django.db.models.ForeignKey.on_delete`
    
  2978. ``DO_NOTHING`` do not prevent taking the fast-path in deletion.
    
  2979. 
    
  2980. Note that the queries generated in object deletion is an implementation
    
  2981. detail subject to change.
    
  2982. 
    
  2983. .. versionchanged:: 4.1
    
  2984. 
    
  2985.     ``adelete()`` method was added.
    
  2986. 
    
  2987. ``as_manager()``
    
  2988. ~~~~~~~~~~~~~~~~
    
  2989. 
    
  2990. .. classmethod:: as_manager()
    
  2991. 
    
  2992. Class method that returns an instance of :class:`~django.db.models.Manager`
    
  2993. with a copy of the ``QuerySet``’s methods. See
    
  2994. :ref:`create-manager-with-queryset-methods` for more details.
    
  2995. 
    
  2996. Note that unlike the other entries in this section, this does not have an
    
  2997. asynchronous variant as it does not execute a query.
    
  2998. 
    
  2999. ``explain()``
    
  3000. ~~~~~~~~~~~~~
    
  3001. 
    
  3002. .. method:: explain(format=None, **options)
    
  3003. .. method:: aexplain(format=None, **options)
    
  3004. 
    
  3005. *Asynchronous version*: ``aexplain()``
    
  3006. 
    
  3007. Returns a string of the ``QuerySet``’s execution plan, which details how the
    
  3008. database would execute the query, including any indexes or joins that would be
    
  3009. used. Knowing these details may help you improve the performance of slow
    
  3010. queries.
    
  3011. 
    
  3012. For example, when using PostgreSQL::
    
  3013. 
    
  3014.     >>> print(Blog.objects.filter(title='My Blog').explain())
    
  3015.     Seq Scan on blog  (cost=0.00..35.50 rows=10 width=12)
    
  3016.       Filter: (title = 'My Blog'::bpchar)
    
  3017. 
    
  3018. The output differs significantly between databases.
    
  3019. 
    
  3020. ``explain()`` is supported by all built-in database backends except Oracle
    
  3021. because an implementation there isn't straightforward.
    
  3022. 
    
  3023. The ``format`` parameter changes the output format from the databases's
    
  3024. default, which is usually text-based. PostgreSQL supports ``'TEXT'``,
    
  3025. ``'JSON'``, ``'YAML'``, and ``'XML'`` formats. MariaDB and MySQL support
    
  3026. ``'TEXT'`` (also called ``'TRADITIONAL'``) and ``'JSON'`` formats. MySQL
    
  3027. 8.0.16+ also supports an improved ``'TREE'`` format, which is similar to
    
  3028. PostgreSQL's ``'TEXT'`` output and is used by default, if supported.
    
  3029. 
    
  3030. Some databases accept flags that can return more information about the query.
    
  3031. Pass these flags as keyword arguments. For example, when using PostgreSQL::
    
  3032. 
    
  3033.     >>> print(Blog.objects.filter(title='My Blog').explain(verbose=True, analyze=True))
    
  3034.     Seq Scan on public.blog  (cost=0.00..35.50 rows=10 width=12) (actual time=0.004..0.004 rows=10 loops=1)
    
  3035.       Output: id, title
    
  3036.       Filter: (blog.title = 'My Blog'::bpchar)
    
  3037.     Planning time: 0.064 ms
    
  3038.     Execution time: 0.058 ms
    
  3039. 
    
  3040. On some databases, flags may cause the query to be executed which could have
    
  3041. adverse effects on your database. For example, the ``ANALYZE`` flag supported
    
  3042. by MariaDB, MySQL 8.0.18+, and PostgreSQL could result in changes to data if
    
  3043. there are triggers or if a function is called, even for a ``SELECT`` query.
    
  3044. 
    
  3045. .. versionchanged:: 4.1
    
  3046. 
    
  3047.     ``aexplain()`` method was added.
    
  3048. 
    
  3049. .. _field-lookups:
    
  3050. 
    
  3051. ``Field`` lookups
    
  3052. -----------------
    
  3053. 
    
  3054. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
    
  3055. specified as keyword arguments to the ``QuerySet`` methods :meth:`filter()`,
    
  3056. :meth:`exclude()` and :meth:`get()`.
    
  3057. 
    
  3058. For an introduction, see :ref:`models and database queries documentation
    
  3059. <field-lookups-intro>`.
    
  3060. 
    
  3061. Django's built-in lookups are listed below. It is also possible to write
    
  3062. :doc:`custom lookups </howto/custom-lookups>` for model fields.
    
  3063. 
    
  3064. As a convenience when no lookup type is provided (like in
    
  3065. ``Entry.objects.get(id=14)``) the lookup type is assumed to be :lookup:`exact`.
    
  3066. 
    
  3067. .. fieldlookup:: exact
    
  3068. 
    
  3069. ``exact``
    
  3070. ~~~~~~~~~
    
  3071. 
    
  3072. Exact match. If the value provided for comparison is ``None``, it will be
    
  3073. interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more details).
    
  3074. 
    
  3075. Examples::
    
  3076. 
    
  3077.     Entry.objects.get(id__exact=14)
    
  3078.     Entry.objects.get(id__exact=None)
    
  3079. 
    
  3080. SQL equivalents:
    
  3081. 
    
  3082. .. code-block:: sql
    
  3083. 
    
  3084.     SELECT ... WHERE id = 14;
    
  3085.     SELECT ... WHERE id IS NULL;
    
  3086. 
    
  3087. .. admonition:: MySQL comparisons
    
  3088. 
    
  3089.     In MySQL, a database table's "collation" setting determines whether
    
  3090.     ``exact`` comparisons are case-sensitive. This is a database setting, *not*
    
  3091.     a Django setting. It's possible to configure your MySQL tables to use
    
  3092.     case-sensitive comparisons, but some trade-offs are involved. For more
    
  3093.     information about this, see the :ref:`collation section <mysql-collation>`
    
  3094.     in the :doc:`databases </ref/databases>` documentation.
    
  3095. 
    
  3096. .. fieldlookup:: iexact
    
  3097. 
    
  3098. ``iexact``
    
  3099. ~~~~~~~~~~
    
  3100. 
    
  3101. Case-insensitive exact match. If the value provided for comparison is ``None``,
    
  3102. it will be interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more
    
  3103. details).
    
  3104. 
    
  3105. Example::
    
  3106. 
    
  3107.     Blog.objects.get(name__iexact='beatles blog')
    
  3108.     Blog.objects.get(name__iexact=None)
    
  3109. 
    
  3110. SQL equivalents:
    
  3111. 
    
  3112. .. code-block:: sql
    
  3113. 
    
  3114.     SELECT ... WHERE name ILIKE 'beatles blog';
    
  3115.     SELECT ... WHERE name IS NULL;
    
  3116. 
    
  3117. Note the first query will match ``'Beatles Blog'``, ``'beatles blog'``,
    
  3118. ``'BeAtLes BLoG'``, etc.
    
  3119. 
    
  3120. .. admonition:: SQLite users
    
  3121. 
    
  3122.     When using the SQLite backend and non-ASCII strings, bear in mind the
    
  3123.     :ref:`database note <sqlite-string-matching>` about string comparisons.
    
  3124.     SQLite does not do case-insensitive matching for non-ASCII strings.
    
  3125. 
    
  3126. .. fieldlookup:: contains
    
  3127. 
    
  3128. ``contains``
    
  3129. ~~~~~~~~~~~~
    
  3130. 
    
  3131. Case-sensitive containment test.
    
  3132. 
    
  3133. Example::
    
  3134. 
    
  3135.     Entry.objects.get(headline__contains='Lennon')
    
  3136. 
    
  3137. SQL equivalent:
    
  3138. 
    
  3139. .. code-block:: sql
    
  3140. 
    
  3141.     SELECT ... WHERE headline LIKE '%Lennon%';
    
  3142. 
    
  3143. Note this will match the headline ``'Lennon honored today'`` but not ``'lennon
    
  3144. honored today'``.
    
  3145. 
    
  3146. .. admonition:: SQLite users
    
  3147. 
    
  3148.     SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains``
    
  3149.     acts like ``icontains`` for SQLite. See the :ref:`database note
    
  3150.     <sqlite-string-matching>` for more information.
    
  3151. 
    
  3152. 
    
  3153. .. fieldlookup:: icontains
    
  3154. 
    
  3155. ``icontains``
    
  3156. ~~~~~~~~~~~~~
    
  3157. 
    
  3158. Case-insensitive containment test.
    
  3159. 
    
  3160. Example::
    
  3161. 
    
  3162.     Entry.objects.get(headline__icontains='Lennon')
    
  3163. 
    
  3164. SQL equivalent:
    
  3165. 
    
  3166. .. code-block:: sql
    
  3167. 
    
  3168.     SELECT ... WHERE headline ILIKE '%Lennon%';
    
  3169. 
    
  3170. .. admonition:: SQLite users
    
  3171. 
    
  3172.     When using the SQLite backend and non-ASCII strings, bear in mind the
    
  3173.     :ref:`database note <sqlite-string-matching>` about string comparisons.
    
  3174. 
    
  3175. .. fieldlookup:: in
    
  3176. 
    
  3177. ``in``
    
  3178. ~~~~~~
    
  3179. 
    
  3180. In a given iterable; often a list, tuple, or queryset. It's not a common use
    
  3181. case, but strings (being iterables) are accepted.
    
  3182. 
    
  3183. Examples::
    
  3184. 
    
  3185.     Entry.objects.filter(id__in=[1, 3, 4])
    
  3186.     Entry.objects.filter(headline__in='abc')
    
  3187. 
    
  3188. SQL equivalents:
    
  3189. 
    
  3190. .. code-block:: sql
    
  3191. 
    
  3192.     SELECT ... WHERE id IN (1, 3, 4);
    
  3193.     SELECT ... WHERE headline IN ('a', 'b', 'c');
    
  3194. 
    
  3195. You can also use a queryset to dynamically evaluate the list of values
    
  3196. instead of providing a list of literal values::
    
  3197. 
    
  3198.     inner_qs = Blog.objects.filter(name__contains='Cheddar')
    
  3199.     entries = Entry.objects.filter(blog__in=inner_qs)
    
  3200. 
    
  3201. This queryset will be evaluated as subselect statement:
    
  3202. 
    
  3203. .. code-block:: sql
    
  3204. 
    
  3205.     SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')
    
  3206. 
    
  3207. If you pass in a ``QuerySet`` resulting from ``values()`` or ``values_list()``
    
  3208. as the value to an ``__in`` lookup, you need to ensure you are only extracting
    
  3209. one field in the result. For example, this will work (filtering on the blog
    
  3210. names)::
    
  3211. 
    
  3212.     inner_qs = Blog.objects.filter(name__contains='Ch').values('name')
    
  3213.     entries = Entry.objects.filter(blog__name__in=inner_qs)
    
  3214. 
    
  3215. This example will raise an exception, since the inner query is trying to
    
  3216. extract two field values, where only one is expected::
    
  3217. 
    
  3218.     # Bad code! Will raise a TypeError.
    
  3219.     inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id')
    
  3220.     entries = Entry.objects.filter(blog__name__in=inner_qs)
    
  3221. 
    
  3222. .. _nested-queries-performance:
    
  3223. 
    
  3224. .. admonition:: Performance considerations
    
  3225. 
    
  3226.     Be cautious about using nested queries and understand your database
    
  3227.     server's performance characteristics (if in doubt, benchmark!). Some
    
  3228.     database backends, most notably MySQL, don't optimize nested queries very
    
  3229.     well. It is more efficient, in those cases, to extract a list of values
    
  3230.     and then pass that into the second query. That is, execute two queries
    
  3231.     instead of one::
    
  3232. 
    
  3233.         values = Blog.objects.filter(
    
  3234.                 name__contains='Cheddar').values_list('pk', flat=True)
    
  3235.         entries = Entry.objects.filter(blog__in=list(values))
    
  3236. 
    
  3237.     Note the ``list()`` call around the Blog ``QuerySet`` to force execution of
    
  3238.     the first query. Without it, a nested query would be executed, because
    
  3239.     :ref:`querysets-are-lazy`.
    
  3240. 
    
  3241. .. fieldlookup:: gt
    
  3242. 
    
  3243. ``gt``
    
  3244. ~~~~~~
    
  3245. 
    
  3246. Greater than.
    
  3247. 
    
  3248. Example::
    
  3249. 
    
  3250.     Entry.objects.filter(id__gt=4)
    
  3251. 
    
  3252. SQL equivalent:
    
  3253. 
    
  3254. .. code-block:: sql
    
  3255. 
    
  3256.     SELECT ... WHERE id > 4;
    
  3257. 
    
  3258. .. fieldlookup:: gte
    
  3259. 
    
  3260. ``gte``
    
  3261. ~~~~~~~
    
  3262. 
    
  3263. Greater than or equal to.
    
  3264. 
    
  3265. .. fieldlookup:: lt
    
  3266. 
    
  3267. ``lt``
    
  3268. ~~~~~~
    
  3269. 
    
  3270. Less than.
    
  3271. 
    
  3272. .. fieldlookup:: lte
    
  3273. 
    
  3274. ``lte``
    
  3275. ~~~~~~~
    
  3276. 
    
  3277. Less than or equal to.
    
  3278. 
    
  3279. .. fieldlookup:: startswith
    
  3280. 
    
  3281. ``startswith``
    
  3282. ~~~~~~~~~~~~~~
    
  3283. 
    
  3284. Case-sensitive starts-with.
    
  3285. 
    
  3286. Example::
    
  3287. 
    
  3288.     Entry.objects.filter(headline__startswith='Lennon')
    
  3289. 
    
  3290. SQL equivalent:
    
  3291. 
    
  3292. .. code-block:: sql
    
  3293. 
    
  3294.     SELECT ... WHERE headline LIKE 'Lennon%';
    
  3295. 
    
  3296. SQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts
    
  3297. like ``istartswith`` for SQLite.
    
  3298. 
    
  3299. .. fieldlookup:: istartswith
    
  3300. 
    
  3301. ``istartswith``
    
  3302. ~~~~~~~~~~~~~~~
    
  3303. 
    
  3304. Case-insensitive starts-with.
    
  3305. 
    
  3306. Example::
    
  3307. 
    
  3308.     Entry.objects.filter(headline__istartswith='Lennon')
    
  3309. 
    
  3310. SQL equivalent:
    
  3311. 
    
  3312. .. code-block:: sql
    
  3313. 
    
  3314.     SELECT ... WHERE headline ILIKE 'Lennon%';
    
  3315. 
    
  3316. .. admonition:: SQLite users
    
  3317. 
    
  3318.     When using the SQLite backend and non-ASCII strings, bear in mind the
    
  3319.     :ref:`database note <sqlite-string-matching>` about string comparisons.
    
  3320. 
    
  3321. .. fieldlookup:: endswith
    
  3322. 
    
  3323. ``endswith``
    
  3324. ~~~~~~~~~~~~
    
  3325. 
    
  3326. Case-sensitive ends-with.
    
  3327. 
    
  3328. Example::
    
  3329. 
    
  3330.     Entry.objects.filter(headline__endswith='Lennon')
    
  3331. 
    
  3332. SQL equivalent:
    
  3333. 
    
  3334. .. code-block:: sql
    
  3335. 
    
  3336.     SELECT ... WHERE headline LIKE '%Lennon';
    
  3337. 
    
  3338. .. admonition:: SQLite users
    
  3339. 
    
  3340.     SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith``
    
  3341.     acts like ``iendswith`` for SQLite. Refer to the :ref:`database note
    
  3342.     <sqlite-string-matching>` documentation for more.
    
  3343. 
    
  3344. .. fieldlookup:: iendswith
    
  3345. 
    
  3346. ``iendswith``
    
  3347. ~~~~~~~~~~~~~
    
  3348. 
    
  3349. Case-insensitive ends-with.
    
  3350. 
    
  3351. Example::
    
  3352. 
    
  3353.     Entry.objects.filter(headline__iendswith='Lennon')
    
  3354. 
    
  3355. SQL equivalent:
    
  3356. 
    
  3357. .. code-block:: sql
    
  3358. 
    
  3359.     SELECT ... WHERE headline ILIKE '%Lennon'
    
  3360. 
    
  3361. .. admonition:: SQLite users
    
  3362. 
    
  3363.     When using the SQLite backend and non-ASCII strings, bear in mind the
    
  3364.     :ref:`database note <sqlite-string-matching>` about string comparisons.
    
  3365. 
    
  3366. .. fieldlookup:: range
    
  3367. 
    
  3368. ``range``
    
  3369. ~~~~~~~~~
    
  3370. 
    
  3371. Range test (inclusive).
    
  3372. 
    
  3373. Example::
    
  3374. 
    
  3375.     import datetime
    
  3376.     start_date = datetime.date(2005, 1, 1)
    
  3377.     end_date = datetime.date(2005, 3, 31)
    
  3378.     Entry.objects.filter(pub_date__range=(start_date, end_date))
    
  3379. 
    
  3380. SQL equivalent:
    
  3381. 
    
  3382. .. code-block:: sql
    
  3383. 
    
  3384.     SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
    
  3385. 
    
  3386. You can use ``range`` anywhere you can use ``BETWEEN`` in SQL — for dates,
    
  3387. numbers and even characters.
    
  3388. 
    
  3389. .. warning::
    
  3390. 
    
  3391.     Filtering a ``DateTimeField`` with dates won't include items on the last
    
  3392.     day, because the bounds are interpreted as "0am on the given date". If
    
  3393.     ``pub_date`` was a ``DateTimeField``, the above expression would be turned
    
  3394.     into this SQL:
    
  3395. 
    
  3396.     .. code-block:: sql
    
  3397. 
    
  3398.         SELECT ... WHERE pub_date BETWEEN '2005-01-01 00:00:00' and '2005-03-31 00:00:00';
    
  3399. 
    
  3400.     Generally speaking, you can't mix dates and datetimes.
    
  3401. 
    
  3402. .. fieldlookup:: date
    
  3403. 
    
  3404. ``date``
    
  3405. ~~~~~~~~
    
  3406. 
    
  3407. For datetime fields, casts the value as date. Allows chaining additional field
    
  3408. lookups. Takes a date value.
    
  3409. 
    
  3410. Example::
    
  3411. 
    
  3412.     Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
    
  3413.     Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
    
  3414. 
    
  3415. (No equivalent SQL code fragment is included for this lookup because
    
  3416. implementation of the relevant query varies among different database engines.)
    
  3417. 
    
  3418. When :setting:`USE_TZ` is ``True``, fields are converted to the current time
    
  3419. zone before filtering. This requires :ref:`time zone definitions in the
    
  3420. database <database-time-zone-definitions>`.
    
  3421. 
    
  3422. .. fieldlookup:: year
    
  3423. 
    
  3424. ``year``
    
  3425. ~~~~~~~~
    
  3426. 
    
  3427. For date and datetime fields, an exact year match. Allows chaining additional
    
  3428. field lookups. Takes an integer year.
    
  3429. 
    
  3430. Example::
    
  3431. 
    
  3432.     Entry.objects.filter(pub_date__year=2005)
    
  3433.     Entry.objects.filter(pub_date__year__gte=2005)
    
  3434. 
    
  3435. SQL equivalent:
    
  3436. 
    
  3437. .. code-block:: sql
    
  3438. 
    
  3439.     SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31';
    
  3440.     SELECT ... WHERE pub_date >= '2005-01-01';
    
  3441. 
    
  3442. (The exact SQL syntax varies for each database engine.)
    
  3443. 
    
  3444. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3445. current time zone before filtering. This requires :ref:`time zone definitions
    
  3446. in the database <database-time-zone-definitions>`.
    
  3447. 
    
  3448. .. fieldlookup:: iso_year
    
  3449. 
    
  3450. ``iso_year``
    
  3451. ~~~~~~~~~~~~
    
  3452. 
    
  3453. For date and datetime fields, an exact ISO 8601 week-numbering year match.
    
  3454. Allows chaining additional field lookups. Takes an integer year.
    
  3455. 
    
  3456. Example::
    
  3457. 
    
  3458.     Entry.objects.filter(pub_date__iso_year=2005)
    
  3459.     Entry.objects.filter(pub_date__iso_year__gte=2005)
    
  3460. 
    
  3461. (The exact SQL syntax varies for each database engine.)
    
  3462. 
    
  3463. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3464. current time zone before filtering. This requires :ref:`time zone definitions
    
  3465. in the database <database-time-zone-definitions>`.
    
  3466. 
    
  3467. .. fieldlookup:: month
    
  3468. 
    
  3469. ``month``
    
  3470. ~~~~~~~~~
    
  3471. 
    
  3472. For date and datetime fields, an exact month match. Allows chaining additional
    
  3473. field lookups. Takes an integer 1 (January) through 12 (December).
    
  3474. 
    
  3475. Example::
    
  3476. 
    
  3477.     Entry.objects.filter(pub_date__month=12)
    
  3478.     Entry.objects.filter(pub_date__month__gte=6)
    
  3479. 
    
  3480. SQL equivalent:
    
  3481. 
    
  3482. .. code-block:: sql
    
  3483. 
    
  3484.     SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
    
  3485.     SELECT ... WHERE EXTRACT('month' FROM pub_date) >= '6';
    
  3486. 
    
  3487. (The exact SQL syntax varies for each database engine.)
    
  3488. 
    
  3489. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3490. current time zone before filtering. This requires :ref:`time zone definitions
    
  3491. in the database <database-time-zone-definitions>`.
    
  3492. 
    
  3493. .. fieldlookup:: day
    
  3494. 
    
  3495. ``day``
    
  3496. ~~~~~~~
    
  3497. 
    
  3498. For date and datetime fields, an exact day match. Allows chaining additional
    
  3499. field lookups. Takes an integer day.
    
  3500. 
    
  3501. Example::
    
  3502. 
    
  3503.     Entry.objects.filter(pub_date__day=3)
    
  3504.     Entry.objects.filter(pub_date__day__gte=3)
    
  3505. 
    
  3506. SQL equivalent:
    
  3507. 
    
  3508. .. code-block:: sql
    
  3509. 
    
  3510.     SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
    
  3511.     SELECT ... WHERE EXTRACT('day' FROM pub_date) >= '3';
    
  3512. 
    
  3513. (The exact SQL syntax varies for each database engine.)
    
  3514. 
    
  3515. Note this will match any record with a pub_date on the third day of the month,
    
  3516. such as January 3, July 3, etc.
    
  3517. 
    
  3518. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3519. current time zone before filtering. This requires :ref:`time zone definitions
    
  3520. in the database <database-time-zone-definitions>`.
    
  3521. 
    
  3522. .. fieldlookup:: week
    
  3523. 
    
  3524. ``week``
    
  3525. ~~~~~~~~
    
  3526. 
    
  3527. For date and datetime fields, return the week number (1-52 or 53) according
    
  3528. to `ISO-8601 <https://en.wikipedia.org/wiki/ISO-8601>`_, i.e., weeks start
    
  3529. on a Monday and the first week contains the year's first Thursday.
    
  3530. 
    
  3531. Example::
    
  3532. 
    
  3533.     Entry.objects.filter(pub_date__week=52)
    
  3534.     Entry.objects.filter(pub_date__week__gte=32, pub_date__week__lte=38)
    
  3535. 
    
  3536. (No equivalent SQL code fragment is included for this lookup because
    
  3537. implementation of the relevant query varies among different database engines.)
    
  3538. 
    
  3539. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3540. current time zone before filtering. This requires :ref:`time zone definitions
    
  3541. in the database <database-time-zone-definitions>`.
    
  3542. 
    
  3543. .. fieldlookup:: week_day
    
  3544. 
    
  3545. ``week_day``
    
  3546. ~~~~~~~~~~~~
    
  3547. 
    
  3548. For date and datetime fields, a 'day of the week' match. Allows chaining
    
  3549. additional field lookups.
    
  3550. 
    
  3551. Takes an integer value representing the day of week from 1 (Sunday) to 7
    
  3552. (Saturday).
    
  3553. 
    
  3554. Example::
    
  3555. 
    
  3556.     Entry.objects.filter(pub_date__week_day=2)
    
  3557.     Entry.objects.filter(pub_date__week_day__gte=2)
    
  3558. 
    
  3559. (No equivalent SQL code fragment is included for this lookup because
    
  3560. implementation of the relevant query varies among different database engines.)
    
  3561. 
    
  3562. Note this will match any record with a ``pub_date`` that falls on a Monday (day
    
  3563. 2 of the week), regardless of the month or year in which it occurs. Week days
    
  3564. are indexed with day 1 being Sunday and day 7 being Saturday.
    
  3565. 
    
  3566. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3567. current time zone before filtering. This requires :ref:`time zone definitions
    
  3568. in the database <database-time-zone-definitions>`.
    
  3569. 
    
  3570. .. fieldlookup:: iso_week_day
    
  3571. 
    
  3572. ``iso_week_day``
    
  3573. ~~~~~~~~~~~~~~~~
    
  3574. 
    
  3575. For date and datetime fields, an exact ISO 8601 day of the week match. Allows
    
  3576. chaining additional field lookups.
    
  3577. 
    
  3578. Takes an integer value representing the day of the week from 1 (Monday) to 7
    
  3579. (Sunday).
    
  3580. 
    
  3581. Example::
    
  3582. 
    
  3583.     Entry.objects.filter(pub_date__iso_week_day=1)
    
  3584.     Entry.objects.filter(pub_date__iso_week_day__gte=1)
    
  3585. 
    
  3586. (No equivalent SQL code fragment is included for this lookup because
    
  3587. implementation of the relevant query varies among different database engines.)
    
  3588. 
    
  3589. Note this will match any record with a ``pub_date`` that falls on a Monday (day
    
  3590. 1 of the week), regardless of the month or year in which it occurs. Week days
    
  3591. are indexed with day 1 being Monday and day 7 being Sunday.
    
  3592. 
    
  3593. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3594. current time zone before filtering. This requires :ref:`time zone definitions
    
  3595. in the database <database-time-zone-definitions>`.
    
  3596. 
    
  3597. .. fieldlookup:: quarter
    
  3598. 
    
  3599. ``quarter``
    
  3600. ~~~~~~~~~~~
    
  3601. 
    
  3602. For date and datetime fields, a 'quarter of the year' match. Allows chaining
    
  3603. additional field lookups. Takes an integer value between 1 and 4 representing
    
  3604. the quarter of the year.
    
  3605. 
    
  3606. Example to retrieve entries in the second quarter (April 1 to June 30)::
    
  3607. 
    
  3608.     Entry.objects.filter(pub_date__quarter=2)
    
  3609. 
    
  3610. (No equivalent SQL code fragment is included for this lookup because
    
  3611. implementation of the relevant query varies among different database engines.)
    
  3612. 
    
  3613. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3614. current time zone before filtering. This requires :ref:`time zone definitions
    
  3615. in the database <database-time-zone-definitions>`.
    
  3616. 
    
  3617. .. fieldlookup:: time
    
  3618. 
    
  3619. ``time``
    
  3620. ~~~~~~~~
    
  3621. 
    
  3622. For datetime fields, casts the value as time. Allows chaining additional field
    
  3623. lookups. Takes a :class:`datetime.time` value.
    
  3624. 
    
  3625. Example::
    
  3626. 
    
  3627.     Entry.objects.filter(pub_date__time=datetime.time(14, 30))
    
  3628.     Entry.objects.filter(pub_date__time__range=(datetime.time(8), datetime.time(17)))
    
  3629. 
    
  3630. (No equivalent SQL code fragment is included for this lookup because
    
  3631. implementation of the relevant query varies among different database engines.)
    
  3632. 
    
  3633. When :setting:`USE_TZ` is ``True``, fields are converted to the current time
    
  3634. zone before filtering. This requires :ref:`time zone definitions in the
    
  3635. database <database-time-zone-definitions>`.
    
  3636. 
    
  3637. .. fieldlookup:: hour
    
  3638. 
    
  3639. ``hour``
    
  3640. ~~~~~~~~
    
  3641. 
    
  3642. For datetime and time fields, an exact hour match. Allows chaining additional
    
  3643. field lookups. Takes an integer between 0 and 23.
    
  3644. 
    
  3645. Example::
    
  3646. 
    
  3647.     Event.objects.filter(timestamp__hour=23)
    
  3648.     Event.objects.filter(time__hour=5)
    
  3649.     Event.objects.filter(timestamp__hour__gte=12)
    
  3650. 
    
  3651. SQL equivalent:
    
  3652. 
    
  3653. .. code-block:: sql
    
  3654. 
    
  3655.     SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';
    
  3656.     SELECT ... WHERE EXTRACT('hour' FROM time) = '5';
    
  3657.     SELECT ... WHERE EXTRACT('hour' FROM timestamp) >= '12';
    
  3658. 
    
  3659. (The exact SQL syntax varies for each database engine.)
    
  3660. 
    
  3661. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3662. current time zone before filtering. This requires :ref:`time zone definitions
    
  3663. in the database <database-time-zone-definitions>`.
    
  3664. 
    
  3665. .. fieldlookup:: minute
    
  3666. 
    
  3667. ``minute``
    
  3668. ~~~~~~~~~~
    
  3669. 
    
  3670. For datetime and time fields, an exact minute match. Allows chaining additional
    
  3671. field lookups. Takes an integer between 0 and 59.
    
  3672. 
    
  3673. Example::
    
  3674. 
    
  3675.     Event.objects.filter(timestamp__minute=29)
    
  3676.     Event.objects.filter(time__minute=46)
    
  3677.     Event.objects.filter(timestamp__minute__gte=29)
    
  3678. 
    
  3679. SQL equivalent:
    
  3680. 
    
  3681. .. code-block:: sql
    
  3682. 
    
  3683.     SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';
    
  3684.     SELECT ... WHERE EXTRACT('minute' FROM time) = '46';
    
  3685.     SELECT ... WHERE EXTRACT('minute' FROM timestamp) >= '29';
    
  3686. 
    
  3687. (The exact SQL syntax varies for each database engine.)
    
  3688. 
    
  3689. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3690. current time zone before filtering. This requires :ref:`time zone definitions
    
  3691. in the database <database-time-zone-definitions>`.
    
  3692. 
    
  3693. .. fieldlookup:: second
    
  3694. 
    
  3695. ``second``
    
  3696. ~~~~~~~~~~
    
  3697. 
    
  3698. For datetime and time fields, an exact second match. Allows chaining additional
    
  3699. field lookups. Takes an integer between 0 and 59.
    
  3700. 
    
  3701. Example::
    
  3702. 
    
  3703.     Event.objects.filter(timestamp__second=31)
    
  3704.     Event.objects.filter(time__second=2)
    
  3705.     Event.objects.filter(timestamp__second__gte=31)
    
  3706. 
    
  3707. SQL equivalent:
    
  3708. 
    
  3709. .. code-block:: sql
    
  3710. 
    
  3711.     SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';
    
  3712.     SELECT ... WHERE EXTRACT('second' FROM time) = '2';
    
  3713.     SELECT ... WHERE EXTRACT('second' FROM timestamp) >= '31';
    
  3714. 
    
  3715. (The exact SQL syntax varies for each database engine.)
    
  3716. 
    
  3717. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
    
  3718. current time zone before filtering. This requires :ref:`time zone definitions
    
  3719. in the database <database-time-zone-definitions>`.
    
  3720. 
    
  3721. .. fieldlookup:: isnull
    
  3722. 
    
  3723. ``isnull``
    
  3724. ~~~~~~~~~~
    
  3725. 
    
  3726. Takes either ``True`` or ``False``, which correspond to SQL queries of
    
  3727. ``IS NULL`` and ``IS NOT NULL``, respectively.
    
  3728. 
    
  3729. Example::
    
  3730. 
    
  3731.     Entry.objects.filter(pub_date__isnull=True)
    
  3732. 
    
  3733. SQL equivalent:
    
  3734. 
    
  3735. .. code-block:: sql
    
  3736. 
    
  3737.     SELECT ... WHERE pub_date IS NULL;
    
  3738. 
    
  3739. .. fieldlookup:: regex
    
  3740. 
    
  3741. ``regex``
    
  3742. ~~~~~~~~~
    
  3743. 
    
  3744. Case-sensitive regular expression match.
    
  3745. 
    
  3746. The regular expression syntax is that of the database backend in use.
    
  3747. In the case of SQLite, which has no built in regular expression support,
    
  3748. this feature is provided by a (Python) user-defined REGEXP function, and
    
  3749. the regular expression syntax is therefore that of Python's ``re`` module.
    
  3750. 
    
  3751. Example::
    
  3752. 
    
  3753.     Entry.objects.get(title__regex=r'^(An?|The) +')
    
  3754. 
    
  3755. SQL equivalents:
    
  3756. 
    
  3757. .. code-block:: sql
    
  3758. 
    
  3759.     SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL
    
  3760. 
    
  3761.     SELECT ... WHERE REGEXP_LIKE(title, '^(An?|The) +', 'c'); -- Oracle
    
  3762. 
    
  3763.     SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL
    
  3764. 
    
  3765.     SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite
    
  3766. 
    
  3767. Using raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the
    
  3768. regular expression syntax is recommended.
    
  3769. 
    
  3770. .. fieldlookup:: iregex
    
  3771. 
    
  3772. ``iregex``
    
  3773. ~~~~~~~~~~
    
  3774. 
    
  3775. Case-insensitive regular expression match.
    
  3776. 
    
  3777. Example::
    
  3778. 
    
  3779.     Entry.objects.get(title__iregex=r'^(an?|the) +')
    
  3780. 
    
  3781. SQL equivalents:
    
  3782. 
    
  3783. .. code-block:: sql
    
  3784. 
    
  3785.     SELECT ... WHERE title REGEXP '^(an?|the) +'; -- MySQL
    
  3786. 
    
  3787.     SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'i'); -- Oracle
    
  3788. 
    
  3789.     SELECT ... WHERE title ~* '^(an?|the) +'; -- PostgreSQL
    
  3790. 
    
  3791.     SELECT ... WHERE title REGEXP '(?i)^(an?|the) +'; -- SQLite
    
  3792. 
    
  3793. .. _aggregation-functions:
    
  3794. 
    
  3795. Aggregation functions
    
  3796. ---------------------
    
  3797. 
    
  3798. .. currentmodule:: django.db.models
    
  3799. 
    
  3800. Django provides the following aggregation functions in the
    
  3801. ``django.db.models`` module. For details on how to use these
    
  3802. aggregate functions, see :doc:`the topic guide on aggregation
    
  3803. </topics/db/aggregation>`. See the :class:`~django.db.models.Aggregate`
    
  3804. documentation to learn how to create your aggregates.
    
  3805. 
    
  3806. .. warning::
    
  3807. 
    
  3808.     SQLite can't handle aggregation on date/time fields out of the box.
    
  3809.     This is because there are no native date/time fields in SQLite and Django
    
  3810.     currently emulates these features using a text field. Attempts to use
    
  3811.     aggregation on date/time fields in SQLite will raise ``NotSupportedError``.
    
  3812. 
    
  3813. .. admonition:: Note
    
  3814. 
    
  3815.     Aggregation functions return ``None`` when used with an empty
    
  3816.     ``QuerySet``. For example, the ``Sum`` aggregation function returns ``None``
    
  3817.     instead of ``0`` if the ``QuerySet`` contains no entries. To return another
    
  3818.     value instead, pass a value to the ``default`` argument. An exception is
    
  3819.     ``Count``, which does return ``0`` if the ``QuerySet`` is empty. ``Count``
    
  3820.     does not support the ``default`` argument.
    
  3821. 
    
  3822. All aggregates have the following parameters in common:
    
  3823. 
    
  3824. ``expressions``
    
  3825. ~~~~~~~~~~~~~~~
    
  3826. 
    
  3827. Strings that reference fields on the model, transforms of the field, or
    
  3828. :doc:`query expressions </ref/models/expressions>`.
    
  3829. 
    
  3830. ``output_field``
    
  3831. ~~~~~~~~~~~~~~~~
    
  3832. 
    
  3833. An optional argument that represents the :doc:`model field </ref/models/fields>`
    
  3834. of the return value
    
  3835. 
    
  3836. .. note::
    
  3837. 
    
  3838.     When combining multiple field types, Django can only determine the
    
  3839.     ``output_field`` if all fields are of the same type. Otherwise, you
    
  3840.     must provide the ``output_field`` yourself.
    
  3841. 
    
  3842. .. _aggregate-filter:
    
  3843. 
    
  3844. ``filter``
    
  3845. ~~~~~~~~~~
    
  3846. 
    
  3847. An optional :class:`Q object <django.db.models.Q>` that's used to filter the
    
  3848. rows that are aggregated.
    
  3849. 
    
  3850. See :ref:`conditional-aggregation` and :ref:`filtering-on-annotations` for
    
  3851. example usage.
    
  3852. 
    
  3853. .. _aggregate-default:
    
  3854. 
    
  3855. ``default``
    
  3856. ~~~~~~~~~~~
    
  3857. 
    
  3858. .. versionadded:: 4.0
    
  3859. 
    
  3860. An optional argument that allows specifying a value to use as a default value
    
  3861. when the queryset (or grouping) contains no entries.
    
  3862. 
    
  3863. ``**extra``
    
  3864. ~~~~~~~~~~~
    
  3865. 
    
  3866. Keyword arguments that can provide extra context for the SQL generated
    
  3867. by the aggregate.
    
  3868. 
    
  3869. ``Avg``
    
  3870. ~~~~~~~
    
  3871. 
    
  3872. .. class:: Avg(expression, output_field=None, distinct=False, filter=None, default=None, **extra)
    
  3873. 
    
  3874.     Returns the mean value of the given expression, which must be numeric
    
  3875.     unless you specify a different ``output_field``.
    
  3876. 
    
  3877.     * Default alias: ``<field>__avg``
    
  3878.     * Return type: ``float`` if input is ``int``, otherwise same as input
    
  3879.       field, or ``output_field`` if supplied
    
  3880. 
    
  3881.     .. attribute:: distinct
    
  3882. 
    
  3883.         Optional. If ``distinct=True``, ``Avg`` returns the mean value of
    
  3884.         unique values. This is the SQL equivalent of ``AVG(DISTINCT <field>)``.
    
  3885.         The default value is ``False``.
    
  3886. 
    
  3887. ``Count``
    
  3888. ~~~~~~~~~
    
  3889. 
    
  3890. .. class:: Count(expression, distinct=False, filter=None, **extra)
    
  3891. 
    
  3892.     Returns the number of objects that are related through the provided
    
  3893.     expression.
    
  3894. 
    
  3895.     * Default alias: ``<field>__count``
    
  3896.     * Return type: ``int``
    
  3897. 
    
  3898.     .. attribute:: distinct
    
  3899. 
    
  3900.         Optional. If ``distinct=True``, the count will only include unique
    
  3901.         instances. This is the SQL equivalent of ``COUNT(DISTINCT <field>)``.
    
  3902.         The default value is ``False``.
    
  3903. 
    
  3904.     .. note::
    
  3905. 
    
  3906.         The ``default`` argument is not supported.
    
  3907. 
    
  3908. ``Max``
    
  3909. ~~~~~~~
    
  3910. 
    
  3911. .. class:: Max(expression, output_field=None, filter=None, default=None, **extra)
    
  3912. 
    
  3913.     Returns the maximum value of the given expression.
    
  3914. 
    
  3915.     * Default alias: ``<field>__max``
    
  3916.     * Return type: same as input field, or ``output_field`` if supplied
    
  3917. 
    
  3918. ``Min``
    
  3919. ~~~~~~~
    
  3920. 
    
  3921. .. class:: Min(expression, output_field=None, filter=None, default=None, **extra)
    
  3922. 
    
  3923.     Returns the minimum value of the given expression.
    
  3924. 
    
  3925.     * Default alias: ``<field>__min``
    
  3926.     * Return type: same as input field, or ``output_field`` if supplied
    
  3927. 
    
  3928. ``StdDev``
    
  3929. ~~~~~~~~~~
    
  3930. 
    
  3931. .. class:: StdDev(expression, output_field=None, sample=False, filter=None, default=None, **extra)
    
  3932. 
    
  3933.     Returns the standard deviation of the data in the provided expression.
    
  3934. 
    
  3935.     * Default alias: ``<field>__stddev``
    
  3936.     * Return type: ``float`` if input is ``int``, otherwise same as input
    
  3937.       field, or ``output_field`` if supplied
    
  3938. 
    
  3939.     .. attribute:: sample
    
  3940. 
    
  3941.         Optional. By default, ``StdDev`` returns the population standard
    
  3942.         deviation. However, if ``sample=True``, the return value will be the
    
  3943.         sample standard deviation.
    
  3944. 
    
  3945. ``Sum``
    
  3946. ~~~~~~~
    
  3947. 
    
  3948. .. class:: Sum(expression, output_field=None, distinct=False, filter=None, default=None, **extra)
    
  3949. 
    
  3950.     Computes the sum of all values of the given expression.
    
  3951. 
    
  3952.     * Default alias: ``<field>__sum``
    
  3953.     * Return type: same as input field, or ``output_field`` if supplied
    
  3954. 
    
  3955.     .. attribute:: distinct
    
  3956. 
    
  3957.         Optional. If ``distinct=True``, ``Sum`` returns the sum of unique
    
  3958.         values. This is the SQL equivalent of ``SUM(DISTINCT <field>)``. The
    
  3959.         default value is ``False``.
    
  3960. 
    
  3961. ``Variance``
    
  3962. ~~~~~~~~~~~~
    
  3963. 
    
  3964. .. class:: Variance(expression, output_field=None, sample=False, filter=None, default=None, **extra)
    
  3965. 
    
  3966.     Returns the variance of the data in the provided expression.
    
  3967. 
    
  3968.     * Default alias: ``<field>__variance``
    
  3969.     * Return type: ``float`` if input is ``int``, otherwise same as input
    
  3970.       field, or ``output_field`` if supplied
    
  3971. 
    
  3972.     .. attribute:: sample
    
  3973. 
    
  3974.         Optional. By default, ``Variance`` returns the population variance.
    
  3975.         However, if ``sample=True``, the return value will be the sample
    
  3976.         variance.
    
  3977. 
    
  3978. Query-related tools
    
  3979. ===================
    
  3980. 
    
  3981. This section provides reference material for query-related tools not documented
    
  3982. elsewhere.
    
  3983. 
    
  3984. ``Q()`` objects
    
  3985. ---------------
    
  3986. 
    
  3987. .. class:: Q
    
  3988. 
    
  3989. A ``Q()`` object represents an SQL condition that can be used in
    
  3990. database-related operations. It's similar to how an
    
  3991. :class:`F() <django.db.models.F>` object represents the value of a model field
    
  3992. or annotation. They make it possible to define and reuse conditions, and
    
  3993. combine them using operators such as ``|`` (``OR``), ``&`` (``AND``), and ``^``
    
  3994. (``XOR``). See :ref:`complex-lookups-with-q`.
    
  3995. 
    
  3996. .. versionchanged:: 4.1
    
  3997. 
    
  3998.     Support for the ``^`` (``XOR``) operator was added.
    
  3999. 
    
  4000. ``Prefetch()`` objects
    
  4001. ----------------------
    
  4002. 
    
  4003. .. class:: Prefetch(lookup, queryset=None, to_attr=None)
    
  4004. 
    
  4005. The ``Prefetch()`` object can be used to control the operation of
    
  4006. :meth:`~django.db.models.query.QuerySet.prefetch_related()`.
    
  4007. 
    
  4008. The ``lookup`` argument describes the relations to follow and works the same
    
  4009. as the string based lookups passed to
    
  4010. :meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example:
    
  4011. 
    
  4012.     >>> from django.db.models import Prefetch
    
  4013.     >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all()
    
  4014.     <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    
  4015.     # This will only execute two queries regardless of the number of Question
    
  4016.     # and Choice objects.
    
  4017.     >>> Question.objects.prefetch_related(Prefetch('choice_set'))
    
  4018.     <QuerySet [<Question: What's up?>]>
    
  4019. 
    
  4020. The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup.
    
  4021. This is useful to further filter down the prefetch operation, or to call
    
  4022. :meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched
    
  4023. relation, hence reducing the number of queries even further:
    
  4024. 
    
  4025.     >>> voted_choices = Choice.objects.filter(votes__gt=0)
    
  4026.     >>> voted_choices
    
  4027.     <QuerySet [<Choice: The sky>]>
    
  4028.     >>> prefetch = Prefetch('choice_set', queryset=voted_choices)
    
  4029.     >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()
    
  4030.     <QuerySet [<Choice: The sky>]>
    
  4031. 
    
  4032. The ``to_attr`` argument sets the result of the prefetch operation to a custom
    
  4033. attribute:
    
  4034. 
    
  4035.     >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')
    
  4036.     >>> Question.objects.prefetch_related(prefetch).get().voted_choices
    
  4037.     [<Choice: The sky>]
    
  4038.     >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()
    
  4039.     <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    
  4040. 
    
  4041. .. note::
    
  4042. 
    
  4043.     When using ``to_attr`` the prefetched result is stored in a list. This can
    
  4044.     provide a significant speed improvement over traditional
    
  4045.     ``prefetch_related`` calls which store the cached result within a
    
  4046.     ``QuerySet`` instance.
    
  4047. 
    
  4048. ``prefetch_related_objects()``
    
  4049. ------------------------------
    
  4050. 
    
  4051. .. function:: prefetch_related_objects(model_instances, *related_lookups)
    
  4052. 
    
  4053. Prefetches the given lookups on an iterable of model instances. This is useful
    
  4054. in code that receives a list of model instances as opposed to a ``QuerySet``;
    
  4055. for example, when fetching models from a cache or instantiating them manually.
    
  4056. 
    
  4057. Pass an iterable of model instances (must all be of the same class) and the
    
  4058. lookups or :class:`Prefetch` objects you want to prefetch for. For example::
    
  4059. 
    
  4060.     >>> from django.db.models import prefetch_related_objects
    
  4061.     >>> restaurants = fetch_top_restaurants_from_cache()  # A list of Restaurants
    
  4062.     >>> prefetch_related_objects(restaurants, 'pizzas__toppings')
    
  4063. 
    
  4064. When using multiple databases with ``prefetch_related_objects``, the prefetch
    
  4065. query will use the database associated with the model instance. This can be
    
  4066. overridden by using a custom queryset in a related lookup.
    
  4067. 
    
  4068. ``FilteredRelation()`` objects
    
  4069. ------------------------------
    
  4070. 
    
  4071. .. class:: FilteredRelation(relation_name, *, condition=Q())
    
  4072. 
    
  4073.     .. attribute:: FilteredRelation.relation_name
    
  4074. 
    
  4075.         The name of the field on which you'd like to filter the relation.
    
  4076. 
    
  4077.     .. attribute:: FilteredRelation.condition
    
  4078. 
    
  4079.         A :class:`~django.db.models.Q` object to control the filtering.
    
  4080. 
    
  4081. ``FilteredRelation`` is used with :meth:`~.QuerySet.annotate()` to create an
    
  4082. ``ON`` clause when a ``JOIN`` is performed. It doesn't act on the default
    
  4083. relationship but on the annotation name (``pizzas_vegetarian`` in example
    
  4084. below).
    
  4085. 
    
  4086. For example, to find restaurants that have vegetarian pizzas with
    
  4087. ``'mozzarella'`` in the name::
    
  4088. 
    
  4089.     >>> from django.db.models import FilteredRelation, Q
    
  4090.     >>> Restaurant.objects.annotate(
    
  4091.     ...    pizzas_vegetarian=FilteredRelation(
    
  4092.     ...        'pizzas', condition=Q(pizzas__vegetarian=True),
    
  4093.     ...    ),
    
  4094.     ... ).filter(pizzas_vegetarian__name__icontains='mozzarella')
    
  4095. 
    
  4096. If there are a large number of pizzas, this queryset performs better than::
    
  4097. 
    
  4098.     >>> Restaurant.objects.filter(
    
  4099.     ...     pizzas__vegetarian=True,
    
  4100.     ...     pizzas__name__icontains='mozzarella',
    
  4101.     ... )
    
  4102. 
    
  4103. because the filtering in the ``WHERE`` clause of the first queryset will only
    
  4104. operate on vegetarian pizzas.
    
  4105. 
    
  4106. ``FilteredRelation`` doesn't support:
    
  4107. 
    
  4108. * :meth:`.QuerySet.only` and :meth:`~.QuerySet.prefetch_related`.
    
  4109. * A :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
    
  4110.   inherited from a parent model.