querysets.txt 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079
  1. ======================
  2. QuerySet API reference
  3. ======================
  4. .. currentmodule:: django.db.models.query
  5. This document describes the details of the ``QuerySet`` API. It builds on the
  6. material presented in the :doc:`model </topics/db/models>` and :doc:`database
  7. query </topics/db/queries>` guides, so you'll probably want to read and
  8. understand those documents before reading this one.
  9. Throughout this reference we'll use the :ref:`example Weblog models
  10. <queryset-model-example>` presented in the :doc:`database query guide
  11. </topics/db/queries>`.
  12. .. _when-querysets-are-evaluated:
  13. When QuerySets are evaluated
  14. ============================
  15. Internally, a ``QuerySet`` can be constructed, filtered, sliced, and generally
  16. passed around without actually hitting the database. No database activity
  17. actually occurs until you do something to evaluate the queryset.
  18. You can evaluate a ``QuerySet`` in the following ways:
  19. * **Iteration.** A ``QuerySet`` is iterable, and it executes its database
  20. query the first time you iterate over it. For example, this will print
  21. the headline of all entries in the database::
  22. for e in Entry.objects.all():
  23. print(e.headline)
  24. Note: Don't use this if all you want to do is determine if at least one
  25. result exists. It's more efficient to use :meth:`~QuerySet.exists`.
  26. * **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
  27. be sliced, using Python's array-slicing syntax. Slicing an unevaluated
  28. ``QuerySet`` usually returns another unevaluated ``QuerySet``, but Django
  29. will execute the database query if you use the "step" parameter of slice
  30. syntax, and will return a list. Slicing a ``QuerySet`` that has been
  31. evaluated also returns a list.
  32. Also note that even though slicing an unevaluated ``QuerySet`` returns
  33. another unevaluated ``QuerySet``, modifying it further (e.g., adding
  34. more filters, or modifying ordering) is not allowed, since that does not
  35. translate well into SQL and it would not have a clear meaning either.
  36. * **Pickling/Caching.** See the following section for details of what
  37. is involved when `pickling QuerySets`_. The important thing for the
  38. purposes of this section is that the results are read from the database.
  39. * **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
  40. This is for convenience in the Python interactive interpreter, so you can
  41. immediately see your results when using the API interactively.
  42. * **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
  43. This, as you might expect, returns the length of the result list.
  44. Note: If you only need to determine the number of records in the set (and
  45. don't need the actual objects), it's much more efficient to handle a count
  46. at the database level using SQL's ``SELECT COUNT(*)``. Django provides a
  47. :meth:`~QuerySet.count` method for precisely this reason.
  48. * **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
  49. it. For example::
  50. entry_list = list(Entry.objects.all())
  51. * **bool().** Testing a ``QuerySet`` in a boolean context, such as using
  52. ``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query
  53. to be executed. If there is at least one result, the ``QuerySet`` is
  54. ``True``, otherwise ``False``. For example::
  55. if Entry.objects.filter(headline="Test"):
  56. print("There is at least one Entry with the headline Test")
  57. Note: If you only want to determine if at least one result exists (and don't
  58. need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`.
  59. .. _pickling QuerySets:
  60. Pickling QuerySets
  61. ------------------
  62. If you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded
  63. into memory prior to pickling. Pickling is usually used as a precursor to
  64. caching and when the cached queryset is reloaded, you want the results to
  65. already be present and ready for use (reading from the database can take some
  66. time, defeating the purpose of caching). This means that when you unpickle a
  67. ``QuerySet``, it contains the results at the moment it was pickled, rather
  68. than the results that are currently in the database.
  69. If you only want to pickle the necessary information to recreate the
  70. ``QuerySet`` from the database at a later time, pickle the ``query`` attribute
  71. of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
  72. any results loaded) using some code like this::
  73. >>> import pickle
  74. >>> query = pickle.loads(s) # Assuming 's' is the pickled string.
  75. >>> qs = MyModel.objects.all()
  76. >>> qs.query = query # Restore the original 'query'.
  77. The ``query`` attribute is an opaque object. It represents the internals of
  78. the query construction and is not part of the public API. However, it is safe
  79. (and fully supported) to pickle and unpickle the attribute's contents as
  80. described here.
  81. .. admonition:: You can't share pickles between versions
  82. Pickles of ``QuerySets`` are only valid for the version of Django that
  83. was used to generate them. If you generate a pickle using Django
  84. version N, there is no guarantee that pickle will be readable with
  85. Django version N+1. Pickles should not be used as part of a long-term
  86. archival strategy.
  87. .. versionadded:: 1.8
  88. Since pickle compatibility errors can be difficult to diagnose, such as
  89. silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
  90. unpickle a queryset in a Django version that is different than the one in
  91. which it was pickled.
  92. .. _queryset-api:
  93. QuerySet API
  94. ============
  95. Here's the formal declaration of a ``QuerySet``:
  96. .. class:: QuerySet(model=None, query=None, using=None)
  97. Usually when you'll interact with a ``QuerySet`` you'll use it by
  98. :ref:`chaining filters <chaining-filters>`. To make this work, most
  99. ``QuerySet`` methods return new querysets. These methods are covered in
  100. detail later in this section.
  101. The ``QuerySet`` class has two public attributes you can use for
  102. introspection:
  103. .. attribute:: ordered
  104. ``True`` if the ``QuerySet`` is ordered — i.e. has an
  105. :meth:`order_by()` clause or a default ordering on the model.
  106. ``False`` otherwise.
  107. .. attribute:: db
  108. The database that will be used if this query is executed now.
  109. .. note::
  110. The ``query`` parameter to :class:`QuerySet` exists so that specialized
  111. query subclasses such as
  112. :class:`~django.contrib.gis.db.models.GeoQuerySet` can reconstruct
  113. internal query state. The value of the parameter is an opaque
  114. representation of that query state and is not part of a public API.
  115. To put it simply: if you need to ask, you don't need to use it.
  116. .. currentmodule:: django.db.models.query.QuerySet
  117. Methods that return new QuerySets
  118. ---------------------------------
  119. Django provides a range of ``QuerySet`` refinement methods that modify either
  120. the types of results returned by the ``QuerySet`` or the way its SQL query is
  121. executed.
  122. filter
  123. ~~~~~~
  124. .. method:: filter(**kwargs)
  125. Returns a new ``QuerySet`` containing objects that match the given lookup
  126. parameters.
  127. The lookup parameters (``**kwargs``) should be in the format described in
  128. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
  129. underlying SQL statement.
  130. If you need to execute more complex queries (for example, queries with ``OR`` statements),
  131. you can use :class:`Q objects <django.db.models.Q>`.
  132. exclude
  133. ~~~~~~~
  134. .. method:: exclude(**kwargs)
  135. Returns a new ``QuerySet`` containing objects that do *not* match the given
  136. lookup parameters.
  137. The lookup parameters (``**kwargs``) should be in the format described in
  138. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
  139. underlying SQL statement, and the whole thing is enclosed in a ``NOT()``.
  140. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
  141. AND whose ``headline`` is "Hello"::
  142. Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
  143. In SQL terms, that evaluates to::
  144. SELECT ...
  145. WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
  146. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
  147. OR whose headline is "Hello"::
  148. Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
  149. In SQL terms, that evaluates to::
  150. SELECT ...
  151. WHERE NOT pub_date > '2005-1-3'
  152. AND NOT headline = 'Hello'
  153. Note the second example is more restrictive.
  154. If you need to execute more complex queries (for example, queries with ``OR`` statements),
  155. you can use :class:`Q objects <django.db.models.Q>`.
  156. annotate
  157. ~~~~~~~~
  158. .. method:: annotate(*args, **kwargs)
  159. Annotates each object in the ``QuerySet`` with the provided list of :doc:`query
  160. expressions </ref/models/expressions>`. An expression may be a simple value, a
  161. reference to a field on the model (or any related models), or an aggregate
  162. expression (averages, sums, etc) that has been computed over the objects that
  163. are related to the objects in the ``QuerySet``.
  164. .. versionadded:: 1.8
  165. Previous versions of Django only allowed aggregate functions to be used as
  166. annotations. It is now possible to annotate a model with all kinds of
  167. expressions.
  168. Each argument to ``annotate()`` is an annotation that will be added
  169. to each object in the ``QuerySet`` that is returned.
  170. The aggregation functions that are provided by Django are described
  171. in `Aggregation Functions`_ below.
  172. Annotations specified using keyword arguments will use the keyword as
  173. the alias for the annotation. Anonymous arguments will have an alias
  174. generated for them based upon the name of the aggregate function and
  175. the model field that is being aggregated. Only aggregate expressions
  176. that reference a single field can be anonymous arguments. Everything
  177. else must be a keyword argument.
  178. For example, if you were manipulating a list of blogs, you may want
  179. to determine how many entries have been made in each blog::
  180. >>> from django.db.models import Count
  181. >>> q = Blog.objects.annotate(Count('entry'))
  182. # The name of the first blog
  183. >>> q[0].name
  184. 'Blogasaurus'
  185. # The number of entries on the first blog
  186. >>> q[0].entry__count
  187. 42
  188. The ``Blog`` model doesn't define an ``entry__count`` attribute by itself,
  189. but by using a keyword argument to specify the aggregate function, you can
  190. control the name of the annotation::
  191. >>> q = Blog.objects.annotate(number_of_entries=Count('entry'))
  192. # The number of entries on the first blog, using the name provided
  193. >>> q[0].number_of_entries
  194. 42
  195. For an in-depth discussion of aggregation, see :doc:`the topic guide on
  196. Aggregation </topics/db/aggregation>`.
  197. order_by
  198. ~~~~~~~~
  199. .. method:: order_by(*fields)
  200. By default, results returned by a ``QuerySet`` are ordered by the ordering
  201. tuple given by the ``ordering`` option in the model's ``Meta``. You can
  202. override this on a per-``QuerySet`` basis by using the ``order_by`` method.
  203. Example::
  204. Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
  205. The result above will be ordered by ``pub_date`` descending, then by
  206. ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
  207. *descending* order. Ascending order is implied. To order randomly, use ``"?"``,
  208. like so::
  209. Entry.objects.order_by('?')
  210. Note: ``order_by('?')`` queries may be expensive and slow, depending on the
  211. database backend you're using.
  212. To order by a field in a different model, use the same syntax as when you are
  213. querying across model relations. That is, the name of the field, followed by a
  214. double underscore (``__``), followed by the name of the field in the new model,
  215. and so on for as many models as you want to join. For example::
  216. Entry.objects.order_by('blog__name', 'headline')
  217. If you try to order by a field that is a relation to another model, Django will
  218. use the default ordering on the related model, or order by the related model's
  219. primary key if there is no :attr:`Meta.ordering
  220. <django.db.models.Options.ordering>` specified. For example, since the ``Blog``
  221. model has no default ordering specified::
  222. Entry.objects.order_by('blog')
  223. ...is identical to::
  224. Entry.objects.order_by('blog__id')
  225. If ``Blog`` had ``ordering = ['name']``, then the first queryset would be
  226. identical to::
  227. Entry.objects.order_by('blog__name')
  228. It is also possible to order a queryset by a related field, without incurring
  229. the cost of a JOIN, by referring to the ``_id`` of the related field::
  230. # No Join
  231. Entry.objects.order_by('blog_id')
  232. # Join
  233. Entry.objects.order_by('blog__id')
  234. You can also order by :doc:`query expressions </ref/models/expressions>` by
  235. calling ``asc()`` or ``desc()`` on the expression::
  236. Entry.objects.order_by(Coalesce('summary', 'headline').desc())
  237. .. versionadded:: 1.8
  238. Ordering by query expressions was added.
  239. Be cautious when ordering by fields in related models if you are also using
  240. :meth:`distinct()`. See the note in :meth:`distinct` for an explanation of how
  241. related model ordering can change the expected results.
  242. .. note::
  243. It is permissible to specify a multi-valued field to order the results by
  244. (for example, a :class:`~django.db.models.ManyToManyField` field, or the
  245. reverse relation of a :class:`~django.db.models.ForeignKey` field).
  246. Consider this case::
  247. class Event(Model):
  248. parent = models.ForeignKey(
  249. 'self',
  250. on_delete=models.CASCADE,
  251. related_name='children',
  252. )
  253. date = models.DateField()
  254. Event.objects.order_by('children__date')
  255. Here, there could potentially be multiple ordering data for each ``Event``;
  256. each ``Event`` with multiple ``children`` will be returned multiple times
  257. into the new ``QuerySet`` that ``order_by()`` creates. In other words,
  258. using ``order_by()`` on the ``QuerySet`` could return more items than you
  259. were working on to begin with - which is probably neither expected nor
  260. useful.
  261. Thus, take care when using multi-valued field to order the results. **If**
  262. you can be sure that there will only be one ordering piece of data for each
  263. of the items you're ordering, this approach should not present problems. If
  264. not, make sure the results are what you expect.
  265. There's no way to specify whether ordering should be case sensitive. With
  266. respect to case-sensitivity, Django will order results however your database
  267. backend normally orders them.
  268. You can order by a field converted to lowercase with
  269. :class:`~django.db.models.functions.Lower` which will achieve case-consistent
  270. ordering::
  271. Entry.objects.order_by(Lower('headline').desc())
  272. .. versionadded:: 1.8
  273. The ability to order by expressions like ``Lower`` was added.
  274. If you don't want any ordering to be applied to a query, not even the default
  275. ordering, call :meth:`order_by()` with no parameters.
  276. You can tell if a query is ordered or not by checking the
  277. :attr:`.QuerySet.ordered` attribute, which will be ``True`` if the
  278. ``QuerySet`` has been ordered in any way.
  279. Each ``order_by()`` call will clear any previous ordering. For example, this
  280. query will be ordered by ``pub_date`` and not ``headline``::
  281. Entry.objects.order_by('headline').order_by('pub_date')
  282. .. warning::
  283. Ordering is not a free operation. Each field you add to the ordering
  284. incurs a cost to your database. Each foreign key you add will
  285. implicitly include all of its default orderings as well.
  286. reverse
  287. ~~~~~~~
  288. .. method:: reverse()
  289. Use the ``reverse()`` method to reverse the order in which a queryset's
  290. elements are returned. Calling ``reverse()`` a second time restores the
  291. ordering back to the normal direction.
  292. To retrieve the "last" five items in a queryset, you could do this::
  293. my_queryset.reverse()[:5]
  294. Note that this is not quite the same as slicing from the end of a sequence in
  295. Python. The above example will return the last item first, then the
  296. penultimate item and so on. If we had a Python sequence and looked at
  297. ``seq[-5:]``, we would see the fifth-last item first. Django doesn't support
  298. that mode of access (slicing from the end), because it's not possible to do it
  299. efficiently in SQL.
  300. Also, note that ``reverse()`` should generally only be called on a ``QuerySet``
  301. which has a defined ordering (e.g., when querying against a model which defines
  302. a default ordering, or when using :meth:`order_by()`). If no such ordering is
  303. defined for a given ``QuerySet``, calling ``reverse()`` on it has no real
  304. effect (the ordering was undefined prior to calling ``reverse()``, and will
  305. remain undefined afterward).
  306. distinct
  307. ~~~~~~~~
  308. .. method:: distinct(*fields)
  309. Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
  310. eliminates duplicate rows from the query results.
  311. By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
  312. is rarely a problem, because simple queries such as ``Blog.objects.all()``
  313. don't introduce the possibility of duplicate result rows. However, if your
  314. query spans multiple tables, it's possible to get duplicate results when a
  315. ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
  316. .. note::
  317. Any fields used in an :meth:`order_by` call are included in the SQL
  318. ``SELECT`` columns. This can sometimes lead to unexpected results when used
  319. in conjunction with ``distinct()``. If you order by fields from a related
  320. model, those fields will be added to the selected columns and they may make
  321. otherwise duplicate rows appear to be distinct. Since the extra columns
  322. don't appear in the returned results (they are only there to support
  323. ordering), it sometimes looks like non-distinct results are being returned.
  324. Similarly, if you use a :meth:`values()` query to restrict the columns
  325. selected, the columns used in any :meth:`order_by()` (or default model
  326. ordering) will still be involved and may affect uniqueness of the results.
  327. The moral here is that if you are using ``distinct()`` be careful about
  328. ordering by related models. Similarly, when using ``distinct()`` and
  329. :meth:`values()` together, be careful when ordering by fields not in the
  330. :meth:`values()` call.
  331. On PostgreSQL only, you can pass positional arguments (``*fields``) in order to
  332. specify the names of fields to which the ``DISTINCT`` should apply. This
  333. translates to a ``SELECT DISTINCT ON`` SQL query. Here's the difference. For a
  334. normal ``distinct()`` call, the database compares *each* field in each row when
  335. determining which rows are distinct. For a ``distinct()`` call with specified
  336. field names, the database will only compare the specified field names.
  337. .. note::
  338. When you specify field names, you *must* provide an ``order_by()`` in the
  339. ``QuerySet``, and the fields in ``order_by()`` must start with the fields in
  340. ``distinct()``, in the same order.
  341. For example, ``SELECT DISTINCT ON (a)`` gives you the first row for each
  342. value in column ``a``. If you don't specify an order, you'll get some
  343. arbitrary row.
  344. Examples (those after the first will only work on PostgreSQL)::
  345. >>> Author.objects.distinct()
  346. [...]
  347. >>> Entry.objects.order_by('pub_date').distinct('pub_date')
  348. [...]
  349. >>> Entry.objects.order_by('blog').distinct('blog')
  350. [...]
  351. >>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
  352. [...]
  353. >>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
  354. [...]
  355. >>> Entry.objects.order_by('author', 'pub_date').distinct('author')
  356. [...]
  357. .. note::
  358. Keep in mind that :meth:`order_by` uses any default related model ordering
  359. that has been defined. You might have to explicitly order by the relation
  360. ``_id`` or referenced field to make sure the ``DISTINCT ON`` expressions
  361. match those at the beginning of the ``ORDER BY`` clause. For example, if
  362. the ``Blog`` model defined an :attr:`~django.db.models.Options.ordering` by
  363. ``name``::
  364. Entry.objects.order_by('blog').distinct('blog')
  365. ...wouldn't work because the query would be ordered by ``blog__name`` thus
  366. mismatching the ``DISTINCT ON`` expression. You'd have to explicitly order
  367. by the relation `_id` field (``blog_id`` in this case) or the referenced
  368. one (``blog__pk``) to make sure both expressions match.
  369. values
  370. ~~~~~~
  371. .. method:: values(*fields)
  372. Returns a ``QuerySet`` that returns dictionaries, rather than model instances,
  373. when used as an iterable.
  374. Each of those dictionaries represents an object, with the keys corresponding to
  375. the attribute names of model objects.
  376. This example compares the dictionaries of ``values()`` with the normal model
  377. objects::
  378. # This list contains a Blog object.
  379. >>> Blog.objects.filter(name__startswith='Beatles')
  380. [<Blog: Beatles Blog>]
  381. # This list contains a dictionary.
  382. >>> Blog.objects.filter(name__startswith='Beatles').values()
  383. [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
  384. The ``values()`` method takes optional positional arguments, ``*fields``, which
  385. specify field names to which the ``SELECT`` should be limited. If you specify
  386. the fields, each dictionary will contain only the field keys/values for the
  387. fields you specify. If you don't specify the fields, each dictionary will
  388. contain a key and value for every field in the database table.
  389. Example::
  390. >>> Blog.objects.values()
  391. [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
  392. >>> Blog.objects.values('id', 'name')
  393. [{'id': 1, 'name': 'Beatles Blog'}]
  394. A few subtleties that are worth mentioning:
  395. * If you have a field called ``foo`` that is a
  396. :class:`~django.db.models.ForeignKey`, the default ``values()`` call
  397. will return a dictionary key called ``foo_id``, since this is the name
  398. of the hidden model attribute that stores the actual value (the ``foo``
  399. attribute refers to the related model). When you are calling
  400. ``values()`` and passing in field names, you can pass in either ``foo``
  401. or ``foo_id`` and you will get back the same thing (the dictionary key
  402. will match the field name you passed in).
  403. For example::
  404. >>> Entry.objects.values()
  405. [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]
  406. >>> Entry.objects.values('blog')
  407. [{'blog': 1}, ...]
  408. >>> Entry.objects.values('blog_id')
  409. [{'blog_id': 1}, ...]
  410. * When using ``values()`` together with :meth:`distinct()`, be aware that
  411. ordering can affect the results. See the note in :meth:`distinct` for
  412. details.
  413. * If you use a ``values()`` clause after an :meth:`extra()` call,
  414. any fields defined by a ``select`` argument in the :meth:`extra()` must
  415. be explicitly included in the ``values()`` call. Any :meth:`extra()` call
  416. made after a ``values()`` call will have its extra selected fields
  417. ignored.
  418. * Calling :meth:`only()` and :meth:`defer()` after ``values()`` doesn't make
  419. sense, so doing so will raise a ``NotImplementedError``.
  420. It is useful when you know you're only going to need values from a small number
  421. of the available fields and you won't need the functionality of a model
  422. instance object. It's more efficient to select only the fields you need to use.
  423. Finally, note that you can call ``filter()``, ``order_by()``, etc. after the
  424. ``values()`` call, that means that these two calls are identical::
  425. Blog.objects.values().order_by('id')
  426. Blog.objects.order_by('id').values()
  427. The people who made Django prefer to put all the SQL-affecting methods first,
  428. followed (optionally) by any output-affecting methods (such as ``values()``),
  429. but it doesn't really matter. This is your chance to really flaunt your
  430. individualism.
  431. You can also refer to fields on related models with reverse relations through
  432. ``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes::
  433. Blog.objects.values('name', 'entry__headline')
  434. [{'name': 'My blog', 'entry__headline': 'An entry'},
  435. {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]
  436. .. warning::
  437. Because :class:`~django.db.models.ManyToManyField` attributes and reverse
  438. relations can have multiple related rows, including these can have a
  439. multiplier effect on the size of your result set. This will be especially
  440. pronounced if you include multiple such fields in your ``values()`` query,
  441. in which case all possible combinations will be returned.
  442. values_list
  443. ~~~~~~~~~~~
  444. .. method:: values_list(*fields, flat=False)
  445. This is similar to ``values()`` except that instead of returning dictionaries,
  446. it returns tuples when iterated over. Each tuple contains the value from the
  447. respective field passed into the ``values_list()`` call — so the first item is
  448. the first field, etc. For example::
  449. >>> Entry.objects.values_list('id', 'headline')
  450. [(1, 'First entry'), ...]
  451. If you only pass in a single field, you can also pass in the ``flat``
  452. parameter. If ``True``, this will mean the returned results are single values,
  453. rather than one-tuples. An example should make the difference clearer::
  454. >>> Entry.objects.values_list('id').order_by('id')
  455. [(1,), (2,), (3,), ...]
  456. >>> Entry.objects.values_list('id', flat=True).order_by('id')
  457. [1, 2, 3, ...]
  458. It is an error to pass in ``flat`` when there is more than one field.
  459. If you don't pass any values to ``values_list()``, it will return all the
  460. fields in the model, in the order they were declared.
  461. dates
  462. ~~~~~
  463. .. method:: dates(field, kind, order='ASC')
  464. Returns a ``DateQuerySet`` — a ``QuerySet`` that evaluates to a list of
  465. :class:`datetime.date` objects representing all available dates of a
  466. particular kind within the contents of the ``QuerySet``.
  467. ``field`` should be the name of a ``DateField`` of your model.
  468. ``kind`` should be either ``"year"``, ``"month"`` or ``"day"``. Each
  469. ``datetime.date`` object in the result list is "truncated" to the given
  470. ``type``.
  471. * ``"year"`` returns a list of all distinct year values for the field.
  472. * ``"month"`` returns a list of all distinct year/month values for the
  473. field.
  474. * ``"day"`` returns a list of all distinct year/month/day values for the
  475. field.
  476. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
  477. ``'DESC'``. This specifies how to order the results.
  478. Examples::
  479. >>> Entry.objects.dates('pub_date', 'year')
  480. [datetime.date(2005, 1, 1)]
  481. >>> Entry.objects.dates('pub_date', 'month')
  482. [datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
  483. >>> Entry.objects.dates('pub_date', 'day')
  484. [datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]
  485. >>> Entry.objects.dates('pub_date', 'day', order='DESC')
  486. [datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]
  487. >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
  488. [datetime.date(2005, 3, 20)]
  489. datetimes
  490. ~~~~~~~~~
  491. .. method:: datetimes(field_name, kind, order='ASC', tzinfo=None)
  492. Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.datetime`
  493. objects representing all available dates of a particular kind within the
  494. contents of the ``QuerySet``.
  495. ``field_name`` should be the name of a ``DateTimeField`` of your model.
  496. ``kind`` should be either ``"year"``, ``"month"``, ``"day"``, ``"hour"``,
  497. ``"minute"`` or ``"second"``. Each ``datetime.datetime`` object in the result
  498. list is "truncated" to the given ``type``.
  499. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
  500. ``'DESC'``. This specifies how to order the results.
  501. ``tzinfo`` defines the time zone to which datetimes are converted prior to
  502. truncation. Indeed, a given datetime has different representations depending
  503. on the time zone in use. This parameter must be a :class:`datetime.tzinfo`
  504. object. If it's ``None``, Django uses the :ref:`current time zone
  505. <default-current-time-zone>`. It has no effect when :setting:`USE_TZ` is
  506. ``False``.
  507. .. _database-time-zone-definitions:
  508. .. note::
  509. This function performs time zone conversions directly in the database.
  510. As a consequence, your database must be able to interpret the value of
  511. ``tzinfo.tzname(None)``. This translates into the following requirements:
  512. - SQLite: install pytz_ — conversions are actually performed in Python.
  513. - PostgreSQL: no requirements (see `Time Zones`_).
  514. - Oracle: no requirements (see `Choosing a Time Zone File`_).
  515. - MySQL: install pytz_ and load the time zone tables with
  516. `mysql_tzinfo_to_sql`_.
  517. .. _pytz: http://pytz.sourceforge.net/
  518. .. _Time Zones: http://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONES
  519. .. _Choosing a Time Zone File: http://docs.oracle.com/cd/B19306_01/server.102/b14225/ch4datetime.htm#i1006667
  520. .. _mysql_tzinfo_to_sql: http://dev.mysql.com/doc/refman/5.6/en/mysql-tzinfo-to-sql.html
  521. none
  522. ~~~~
  523. .. method:: none()
  524. Calling none() will create a queryset that never returns any objects and no
  525. query will be executed when accessing the results. A qs.none() queryset
  526. is an instance of ``EmptyQuerySet``.
  527. Examples::
  528. >>> Entry.objects.none()
  529. []
  530. >>> from django.db.models.query import EmptyQuerySet
  531. >>> isinstance(Entry.objects.none(), EmptyQuerySet)
  532. True
  533. all
  534. ~~~
  535. .. method:: all()
  536. Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass). This
  537. can be useful in situations where you might want to pass in either a model
  538. manager or a ``QuerySet`` and do further filtering on the result. After calling
  539. ``all()`` on either object, you'll definitely have a ``QuerySet`` to work with.
  540. When a ``QuerySet`` is :ref:`evaluated <when-querysets-are-evaluated>`, it
  541. typically caches its results. If the data in the database might have changed
  542. since a ``QuerySet`` was evaluated, you can get updated results for the same
  543. query by calling ``all()`` on a previously evaluated ``QuerySet``.
  544. select_related
  545. ~~~~~~~~~~~~~~
  546. .. method:: select_related(*fields)
  547. Returns a ``QuerySet`` that will "follow" foreign-key relationships, selecting
  548. additional related-object data when it executes its query. This is a
  549. performance booster which results in a single more complex query but means
  550. later use of foreign-key relationships won't require database queries.
  551. The following examples illustrate the difference between plain lookups and
  552. ``select_related()`` lookups. Here's standard lookup::
  553. # Hits the database.
  554. e = Entry.objects.get(id=5)
  555. # Hits the database again to get the related Blog object.
  556. b = e.blog
  557. And here's ``select_related`` lookup::
  558. # Hits the database.
  559. e = Entry.objects.select_related('blog').get(id=5)
  560. # Doesn't hit the database, because e.blog has been prepopulated
  561. # in the previous query.
  562. b = e.blog
  563. You can use ``select_related()`` with any queryset of objects::
  564. from django.utils import timezone
  565. # Find all the blogs with entries scheduled to be published in the future.
  566. blogs = set()
  567. for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):
  568. # Without select_related(), this would make a database query for each
  569. # loop iteration in order to fetch the related blog for each entry.
  570. blogs.add(e.blog)
  571. The order of ``filter()`` and ``select_related()`` chaining isn't important.
  572. These querysets are equivalent::
  573. Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')
  574. Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now())
  575. You can follow foreign keys in a similar way to querying them. If you have the
  576. following models::
  577. from django.db import models
  578. class City(models.Model):
  579. # ...
  580. pass
  581. class Person(models.Model):
  582. # ...
  583. hometown = models.ForeignKey(
  584. City,
  585. on_delete=models.SET_NULL,
  586. blank=True,
  587. null=True,
  588. )
  589. class Book(models.Model):
  590. # ...
  591. author = models.ForeignKey(Person, on_delete=models.CASCADE)
  592. ... then a call to ``Book.objects.select_related('author__hometown').get(id=4)``
  593. will cache the related ``Person`` *and* the related ``City``::
  594. b = Book.objects.select_related('author__hometown').get(id=4)
  595. p = b.author # Doesn't hit the database.
  596. c = p.hometown # Doesn't hit the database.
  597. b = Book.objects.get(id=4) # No select_related() in this example.
  598. p = b.author # Hits the database.
  599. c = p.hometown # Hits the database.
  600. You can refer to any :class:`~django.db.models.ForeignKey` or
  601. :class:`~django.db.models.OneToOneField` relation in the list of fields
  602. passed to ``select_related()``.
  603. You can also refer to the reverse direction of a
  604. :class:`~django.db.models.OneToOneField` in the list of fields passed to
  605. ``select_related`` — that is, you can traverse a
  606. :class:`~django.db.models.OneToOneField` back to the object on which the field
  607. is defined. Instead of specifying the field name, use the :attr:`related_name
  608. <django.db.models.ForeignKey.related_name>` for the field on the related object.
  609. There may be some situations where you wish to call ``select_related()`` with a
  610. lot of related objects, or where you don't know all of the relations. In these
  611. cases it is possible to call ``select_related()`` with no arguments. This will
  612. follow all non-null foreign keys it can find - nullable foreign keys must be
  613. specified. This is not recommended in most cases as it is likely to make the
  614. underlying query more complex, and return more data, than is actually needed.
  615. If you need to clear the list of related fields added by past calls of
  616. ``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
  617. >>> without_relations = queryset.select_related(None)
  618. Chaining ``select_related`` calls works in a similar way to other methods -
  619. that is that ``select_related('foo', 'bar')`` is equivalent to
  620. ``select_related('foo').select_related('bar')``.
  621. prefetch_related
  622. ~~~~~~~~~~~~~~~~
  623. .. method:: prefetch_related(*lookups)
  624. Returns a ``QuerySet`` that will automatically retrieve, in a single batch,
  625. related objects for each of the specified lookups.
  626. This has a similar purpose to ``select_related``, in that both are designed to
  627. stop the deluge of database queries that is caused by accessing related objects,
  628. but the strategy is quite different.
  629. ``select_related`` works by creating an SQL join and including the fields of the
  630. related object in the ``SELECT`` statement. For this reason, ``select_related``
  631. gets the related objects in the same database query. However, to avoid the much
  632. larger result set that would result from joining across a 'many' relationship,
  633. ``select_related`` is limited to single-valued relationships - foreign key and
  634. one-to-one.
  635. ``prefetch_related``, on the other hand, does a separate lookup for each
  636. relationship, and does the 'joining' in Python. This allows it to prefetch
  637. many-to-many and many-to-one objects, which cannot be done using
  638. ``select_related``, in addition to the foreign key and one-to-one relationships
  639. that are supported by ``select_related``. It also supports prefetching of
  640. :class:`~django.contrib.contenttypes.fields.GenericRelation` and
  641. :class:`~django.contrib.contenttypes.fields.GenericForeignKey`.
  642. For example, suppose you have these models::
  643. from django.db import models
  644. class Topping(models.Model):
  645. name = models.CharField(max_length=30)
  646. class Pizza(models.Model):
  647. name = models.CharField(max_length=50)
  648. toppings = models.ManyToManyField(Topping)
  649. def __str__(self): # __unicode__ on Python 2
  650. return "%s (%s)" % (self.name, ", ".join(topping.name
  651. for topping in self.toppings.all()))
  652. and run::
  653. >>> Pizza.objects.all()
  654. ["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...
  655. The problem with this is that every time ``Pizza.__str__()`` asks for
  656. ``self.toppings.all()`` it has to query the database, so
  657. ``Pizza.objects.all()`` will run a query on the Toppings table for **every**
  658. item in the Pizza ``QuerySet``.
  659. We can reduce to just two queries using ``prefetch_related``:
  660. >>> Pizza.objects.all().prefetch_related('toppings')
  661. This implies a ``self.toppings.all()`` for each ``Pizza``; now each time
  662. ``self.toppings.all()`` is called, instead of having to go to the database for
  663. the items, it will find them in a prefetched ``QuerySet`` cache that was
  664. populated in a single query.
  665. That is, all the relevant toppings will have been fetched in a single query,
  666. and used to make ``QuerySets`` that have a pre-filled cache of the relevant
  667. results; these ``QuerySets`` are then used in the ``self.toppings.all()`` calls.
  668. The additional queries in ``prefetch_related()`` are executed after the
  669. ``QuerySet`` has begun to be evaluated and the primary query has been executed.
  670. Note that the result cache of the primary ``QuerySet`` and all specified related
  671. objects will then be fully loaded into memory. This changes the typical
  672. behavior of ``QuerySets``, which normally try to avoid loading all objects into
  673. memory before they are needed, even after a query has been executed in the
  674. database.
  675. .. note::
  676. Remember that, as always with ``QuerySets``, any subsequent chained methods
  677. which imply a different database query will ignore previously cached
  678. results, and retrieve data using a fresh database query. So, if you write
  679. the following:
  680. >>> pizzas = Pizza.objects.prefetch_related('toppings')
  681. >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas]
  682. ...then the fact that ``pizza.toppings.all()`` has been prefetched will not
  683. help you. The ``prefetch_related('toppings')`` implied
  684. ``pizza.toppings.all()``, but ``pizza.toppings.filter()`` is a new and
  685. different query. The prefetched cache can't help here; in fact it hurts
  686. performance, since you have done a database query that you haven't used. So
  687. use this feature with caution!
  688. You can also use the normal join syntax to do related fields of related
  689. fields. Suppose we have an additional model to the example above::
  690. class Restaurant(models.Model):
  691. pizzas = models.ManyToMany(Pizza, related_name='restaurants')
  692. best_pizza = models.ForeignKey(Pizza, related_name='championed_by')
  693. The following are all legal:
  694. >>> Restaurant.objects.prefetch_related('pizzas__toppings')
  695. This will prefetch all pizzas belonging to restaurants, and all toppings
  696. belonging to those pizzas. This will result in a total of 3 database queries -
  697. one for the restaurants, one for the pizzas, and one for the toppings.
  698. >>> Restaurant.objects.prefetch_related('best_pizza__toppings')
  699. This will fetch the best pizza and all the toppings for the best pizza for each
  700. restaurant. This will be done in 3 database queries - one for the restaurants,
  701. one for the 'best pizzas', and one for one for the toppings.
  702. Of course, the ``best_pizza`` relationship could also be fetched using
  703. ``select_related`` to reduce the query count to 2:
  704. >>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')
  705. Since the prefetch is executed after the main query (which includes the joins
  706. needed by ``select_related``), it is able to detect that the ``best_pizza``
  707. objects have already been fetched, and it will skip fetching them again.
  708. Chaining ``prefetch_related`` calls will accumulate the lookups that are
  709. prefetched. To clear any ``prefetch_related`` behavior, pass ``None`` as a
  710. parameter:
  711. >>> non_prefetched = qs.prefetch_related(None)
  712. One difference to note when using ``prefetch_related`` is that objects created
  713. by a query can be shared between the different objects that they are related to
  714. i.e. a single Python model instance can appear at more than one point in the
  715. tree of objects that are returned. This will normally happen with foreign key
  716. relationships. Typically this behavior will not be a problem, and will in fact
  717. save both memory and CPU time.
  718. While ``prefetch_related`` supports prefetching ``GenericForeignKey``
  719. relationships, the number of queries will depend on the data. Since a
  720. ``GenericForeignKey`` can reference data in multiple tables, one query per table
  721. referenced is needed, rather than one query for all the items. There could be
  722. additional queries on the ``ContentType`` table if the relevant rows have not
  723. already been fetched.
  724. ``prefetch_related`` in most cases will be implemented using an SQL query that
  725. uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause
  726. could be generated, which, depending on the database, might have performance
  727. problems of its own when it comes to parsing or executing the SQL query. Always
  728. profile for your use case!
  729. Note that if you use ``iterator()`` to run the query, ``prefetch_related()``
  730. calls will be ignored since these two optimizations do not make sense together.
  731. You can use the :class:`~django.db.models.Prefetch` object to further control
  732. the prefetch operation.
  733. In its simplest form ``Prefetch`` is equivalent to the traditional string based
  734. lookups:
  735. >>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings'))
  736. You can provide a custom queryset with the optional ``queryset`` argument.
  737. This can be used to change the default ordering of the queryset:
  738. >>> Restaurant.objects.prefetch_related(
  739. ... Prefetch('pizzas__toppings', queryset=Toppings.objects.order_by('name')))
  740. Or to call :meth:`~django.db.models.query.QuerySet.select_related()` when
  741. applicable to reduce the number of queries even further:
  742. >>> Pizza.objects.prefetch_related(
  743. ... Prefetch('restaurants', queryset=Restaurant.objects.select_related('best_pizza')))
  744. You can also assign the prefetched result to a custom attribute with the optional
  745. ``to_attr`` argument. The result will be stored directly in a list.
  746. This allows prefetching the same relation multiple times with a different
  747. ``QuerySet``; for instance:
  748. >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)
  749. >>> Restaurant.objects.prefetch_related(
  750. ... Prefetch('pizzas', to_attr='menu'),
  751. ... Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'))
  752. Lookups created with custom ``to_attr`` can still be traversed as usual by other
  753. lookups:
  754. >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)
  755. >>> Restaurant.objects.prefetch_related(
  756. ... Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'),
  757. ... 'vegetarian_menu__toppings')
  758. Using ``to_attr`` is recommended when filtering down the prefetch result as it is
  759. less ambiguous than storing a filtered result in the related manager's cache:
  760. >>> queryset = Pizza.objects.filter(vegetarian=True)
  761. >>>
  762. >>> # Recommended:
  763. >>> restaurants = Restaurant.objects.prefetch_related(
  764. ... Prefetch('pizzas', queryset=queryset, to_attr='vegetarian_pizzas'))
  765. >>> vegetarian_pizzas = restaurants[0].vegetarian_pizzas
  766. >>>
  767. >>> # Not recommended:
  768. >>> restaurants = Restaurant.objects.prefetch_related(
  769. ... Prefetch('pizzas', queryset=queryset))
  770. >>> vegetarian_pizzas = restaurants[0].pizzas.all()
  771. Custom prefetching also works with single related relations like
  772. forward ``ForeignKey`` or ``OneToOneField``. Generally you'll want to use
  773. :meth:`select_related()` for these relations, but there are a number of cases
  774. where prefetching with a custom ``QuerySet`` is useful:
  775. * You want to use a ``QuerySet`` that performs further prefetching
  776. on related models.
  777. * You want to prefetch only a subset of the related objects.
  778. * You want to use performance optimization techniques like
  779. :meth:`deferred fields <defer()>`:
  780. >>> queryset = Pizza.objects.only('name')
  781. >>>
  782. >>> restaurants = Restaurant.objects.prefetch_related(
  783. ... Prefetch('best_pizza', queryset=queryset))
  784. .. note::
  785. The ordering of lookups matters.
  786. Take the following examples:
  787. >>> prefetch_related('pizzas__toppings', 'pizzas')
  788. This works even though it's unordered because ``'pizzas__toppings'``
  789. already contains all the needed information, therefore the second argument
  790. ``'pizzas'`` is actually redundant.
  791. >>> prefetch_related('pizzas__toppings', Prefetch('pizzas', queryset=Pizza.objects.all()))
  792. This will raise a ``ValueError`` because of the attempt to redefine the
  793. queryset of a previously seen lookup. Note that an implicit queryset was
  794. created to traverse ``'pizzas'`` as part of the ``'pizzas__toppings'``
  795. lookup.
  796. >>> prefetch_related('pizza_list__toppings', Prefetch('pizzas', to_attr='pizza_list'))
  797. This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't exist yet
  798. when ``'pizza_list__toppings'`` is being processed.
  799. This consideration is not limited to the use of ``Prefetch`` objects. Some
  800. advanced techniques may require that the lookups be performed in a
  801. specific order to avoid creating extra queries; therefore it's recommended
  802. to always carefully order ``prefetch_related`` arguments.
  803. extra
  804. ~~~~~
  805. .. method:: extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
  806. Sometimes, the Django query syntax by itself can't easily express a complex
  807. ``WHERE`` clause. For these edge cases, Django provides the ``extra()``
  808. ``QuerySet`` modifier — a hook for injecting specific clauses into the SQL
  809. generated by a ``QuerySet``.
  810. .. admonition:: Use this method as a last resort
  811. This is an old API that we aim to deprecate at some point in the future.
  812. Use it only if you cannot express your query using other queryset methods.
  813. If you do need to use it, please `file a ticket
  814. <https://code.djangoproject.com/newticket>`_ using the `QuerySet.extra
  815. keyword <https://code.djangoproject.com/query?status=assigned&status=new&keywords=~QuerySet.extra>`_
  816. with your use case (please check the list of existing tickets first) so
  817. that we can enhance the QuerySet API to allow removing ``extra()``. We are
  818. no longer improving or fixing bugs for this method.
  819. For example, this use of ``extra()``::
  820. >>> qs.extra(
  821. ... select={'val': "select col from sometable where othercol = %s"},
  822. ... select_params=(someparam,),
  823. ... )
  824. is equivalent to::
  825. >>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,)))
  826. The main benefit of using :class:`~django.db.models.expressions.RawSQL` is
  827. that you can set ``output_field`` if needed. The main downside is that if
  828. you refer to some table alias of the queryset in the raw SQL, then it is
  829. possible that Django might change that alias (for example, when the
  830. queryset is used as a subquery in yet another query).
  831. .. warning::
  832. You should be very careful whenever you use ``extra()``. Every time you use
  833. it, you should escape any parameters that the user can control by using
  834. ``params`` in order to protect against SQL injection attacks . Please
  835. read more about :ref:`SQL injection protection <sql-injection-protection>`.
  836. By definition, these extra lookups may not be portable to different database
  837. engines (because you're explicitly writing SQL code) and violate the DRY
  838. principle, so you should avoid them if possible.
  839. Specify one or more of ``params``, ``select``, ``where`` or ``tables``. None
  840. of the arguments is required, but you should use at least one of them.
  841. * ``select``
  842. The ``select`` argument lets you put extra fields in the ``SELECT``
  843. clause. It should be a dictionary mapping attribute names to SQL
  844. clauses to use to calculate that attribute.
  845. Example::
  846. Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
  847. As a result, each ``Entry`` object will have an extra attribute,
  848. ``is_recent``, a boolean representing whether the entry's ``pub_date``
  849. is greater than Jan. 1, 2006.
  850. Django inserts the given SQL snippet directly into the ``SELECT``
  851. statement, so the resulting SQL of the above example would be something
  852. like::
  853. SELECT blog_entry.*, (pub_date > '2006-01-01') AS is_recent
  854. FROM blog_entry;
  855. The next example is more advanced; it does a subquery to give each
  856. resulting ``Blog`` object an ``entry_count`` attribute, an integer count
  857. of associated ``Entry`` objects::
  858. Blog.objects.extra(
  859. select={
  860. 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
  861. },
  862. )
  863. In this particular case, we're exploiting the fact that the query will
  864. already contain the ``blog_blog`` table in its ``FROM`` clause.
  865. The resulting SQL of the above example would be::
  866. SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id) AS entry_count
  867. FROM blog_blog;
  868. Note that the parentheses required by most database engines around
  869. subqueries are not required in Django's ``select`` clauses. Also note
  870. that some database backends, such as some MySQL versions, don't support
  871. subqueries.
  872. In some rare cases, you might wish to pass parameters to the SQL
  873. fragments in ``extra(select=...)``. For this purpose, use the
  874. ``select_params`` parameter. Since ``select_params`` is a sequence and
  875. the ``select`` attribute is a dictionary, some care is required so that
  876. the parameters are matched up correctly with the extra select pieces.
  877. In this situation, you should use a :class:`collections.OrderedDict` for
  878. the ``select`` value, not just a normal Python dictionary.
  879. This will work, for example::
  880. Blog.objects.extra(
  881. select=OrderedDict([('a', '%s'), ('b', '%s')]),
  882. select_params=('one', 'two'))
  883. If you need to use a literal ``%s`` inside your select string, use
  884. the sequence ``%%s``.
  885. .. versionchanged:: 1.8
  886. Prior to 1.8, you were unable to escape a literal ``%s``.
  887. * ``where`` / ``tables``
  888. You can define explicit SQL ``WHERE`` clauses — perhaps to perform
  889. non-explicit joins — by using ``where``. You can manually add tables to
  890. the SQL ``FROM`` clause by using ``tables``.
  891. ``where`` and ``tables`` both take a list of strings. All ``where``
  892. parameters are "AND"ed to any other search criteria.
  893. Example::
  894. Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
  895. ...translates (roughly) into the following SQL::
  896. SELECT * FROM blog_entry WHERE (foo='a' OR bar='a') AND (baz='a')
  897. Be careful when using the ``tables`` parameter if you're specifying
  898. tables that are already used in the query. When you add extra tables
  899. via the ``tables`` parameter, Django assumes you want that table
  900. included an extra time, if it is already included. That creates a
  901. problem, since the table name will then be given an alias. If a table
  902. appears multiple times in an SQL statement, the second and subsequent
  903. occurrences must use aliases so the database can tell them apart. If
  904. you're referring to the extra table you added in the extra ``where``
  905. parameter this is going to cause errors.
  906. Normally you'll only be adding extra tables that don't already appear
  907. in the query. However, if the case outlined above does occur, there are
  908. a few solutions. First, see if you can get by without including the
  909. extra table and use the one already in the query. If that isn't
  910. possible, put your ``extra()`` call at the front of the queryset
  911. construction so that your table is the first use of that table.
  912. Finally, if all else fails, look at the query produced and rewrite your
  913. ``where`` addition to use the alias given to your extra table. The
  914. alias will be the same each time you construct the queryset in the same
  915. way, so you can rely upon the alias name to not change.
  916. * ``order_by``
  917. If you need to order the resulting queryset using some of the new
  918. fields or tables you have included via ``extra()`` use the ``order_by``
  919. parameter to ``extra()`` and pass in a sequence of strings. These
  920. strings should either be model fields (as in the normal
  921. :meth:`order_by()` method on querysets), of the form
  922. ``table_name.column_name`` or an alias for a column that you specified
  923. in the ``select`` parameter to ``extra()``.
  924. For example::
  925. q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
  926. q = q.extra(order_by = ['-is_recent'])
  927. This would sort all the items for which ``is_recent`` is true to the
  928. front of the result set (``True`` sorts before ``False`` in a
  929. descending ordering).
  930. This shows, by the way, that you can make multiple calls to ``extra()``
  931. and it will behave as you expect (adding new constraints each time).
  932. * ``params``
  933. The ``where`` parameter described above may use standard Python
  934. database string placeholders — ``'%s'`` to indicate parameters the
  935. database engine should automatically quote. The ``params`` argument is
  936. a list of any extra parameters to be substituted.
  937. Example::
  938. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
  939. Always use ``params`` instead of embedding values directly into
  940. ``where`` because ``params`` will ensure values are quoted correctly
  941. according to your particular backend. For example, quotes will be
  942. escaped correctly.
  943. Bad::
  944. Entry.objects.extra(where=["headline='Lennon'"])
  945. Good::
  946. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
  947. .. warning::
  948. If you are performing queries on MySQL, note that MySQL's silent type coercion
  949. may cause unexpected results when mixing types. If you query on a string
  950. type column, but with an integer value, MySQL will coerce the types of all values
  951. in the table to an integer before performing the comparison. For example, if your
  952. table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
  953. both rows will match. To prevent this, perform the correct typecasting
  954. before using the value in a query.
  955. defer
  956. ~~~~~
  957. .. method:: defer(*fields)
  958. In some complex data-modeling situations, your models might contain a lot of
  959. fields, some of which could contain a lot of data (for example, text fields),
  960. or require expensive processing to convert them to Python objects. If you are
  961. using the results of a queryset in some situation where you don't know
  962. if you need those particular fields when you initially fetch the data, you can
  963. tell Django not to retrieve them from the database.
  964. This is done by passing the names of the fields to not load to ``defer()``::
  965. Entry.objects.defer("headline", "body")
  966. A queryset that has deferred fields will still return model instances. Each
  967. deferred field will be retrieved from the database if you access that field
  968. (one at a time, not all the deferred fields at once).
  969. You can make multiple calls to ``defer()``. Each call adds new fields to the
  970. deferred set::
  971. # Defers both the body and headline fields.
  972. Entry.objects.defer("body").filter(rating=5).defer("headline")
  973. The order in which fields are added to the deferred set does not matter.
  974. Calling ``defer()`` with a field name that has already been deferred is
  975. harmless (the field will still be deferred).
  976. You can defer loading of fields in related models (if the related models are
  977. loading via :meth:`select_related()`) by using the standard double-underscore
  978. notation to separate related fields::
  979. Blog.objects.select_related().defer("entry__headline", "entry__body")
  980. If you want to clear the set of deferred fields, pass ``None`` as a parameter
  981. to ``defer()``::
  982. # Load all fields immediately.
  983. my_queryset.defer(None)
  984. Some fields in a model won't be deferred, even if you ask for them. You can
  985. never defer the loading of the primary key. If you are using
  986. :meth:`select_related()` to retrieve related models, you shouldn't defer the
  987. loading of the field that connects from the primary model to the related
  988. one, doing so will result in an error.
  989. .. note::
  990. The ``defer()`` method (and its cousin, :meth:`only()`, below) are only for
  991. advanced use-cases. They provide an optimization for when you have analyzed
  992. your queries closely and understand *exactly* what information you need and
  993. have measured that the difference between returning the fields you need and
  994. the full set of fields for the model will be significant.
  995. Even if you think you are in the advanced use-case situation, **only use
  996. defer() when you cannot, at queryset load time, determine if you will need
  997. the extra fields or not**. If you are frequently loading and using a
  998. particular subset of your data, the best choice you can make is to
  999. normalize your models and put the non-loaded data into a separate model
  1000. (and database table). If the columns *must* stay in the one table for some
  1001. reason, create a model with ``Meta.managed = False`` (see the
  1002. :attr:`managed attribute <django.db.models.Options.managed>` documentation)
  1003. containing just the fields you normally need to load and use that where you
  1004. might otherwise call ``defer()``. This makes your code more explicit to the
  1005. reader, is slightly faster and consumes a little less memory in the Python
  1006. process.
  1007. For example, both of these models use the same underlying database table::
  1008. class CommonlyUsedModel(models.Model):
  1009. f1 = models.CharField(max_length=10)
  1010. class Meta:
  1011. managed = False
  1012. db_table = 'app_largetable'
  1013. class ManagedModel(models.Model):
  1014. f1 = models.CharField(max_length=10)
  1015. f2 = models.CharField(max_length=10)
  1016. class Meta:
  1017. db_table = 'app_largetable'
  1018. # Two equivalent QuerySets:
  1019. CommonlyUsedModel.objects.all()
  1020. ManagedModel.objects.all().defer('f2')
  1021. If many fields need to be duplicated in the unmanaged model, it may be best
  1022. to create an abstract model with the shared fields and then have the
  1023. unmanaged and managed models inherit from the abstract model.
  1024. .. note::
  1025. When calling :meth:`~django.db.models.Model.save()` for instances with
  1026. deferred fields, only the loaded fields will be saved. See
  1027. :meth:`~django.db.models.Model.save()` for more details.
  1028. only
  1029. ~~~~
  1030. .. method:: only(*fields)
  1031. The ``only()`` method is more or less the opposite of :meth:`defer()`. You call
  1032. it with the fields that should *not* be deferred when retrieving a model. If
  1033. you have a model where almost all the fields need to be deferred, using
  1034. ``only()`` to specify the complementary set of fields can result in simpler
  1035. code.
  1036. Suppose you have a model with fields ``name``, ``age`` and ``biography``. The
  1037. following two querysets are the same, in terms of deferred fields::
  1038. Person.objects.defer("age", "biography")
  1039. Person.objects.only("name")
  1040. Whenever you call ``only()`` it *replaces* the set of fields to load
  1041. immediately. The method's name is mnemonic: **only** those fields are loaded
  1042. immediately; the remainder are deferred. Thus, successive calls to ``only()``
  1043. result in only the final fields being considered::
  1044. # This will defer all fields except the headline.
  1045. Entry.objects.only("body", "rating").only("headline")
  1046. Since ``defer()`` acts incrementally (adding fields to the deferred list), you
  1047. can combine calls to ``only()`` and ``defer()`` and things will behave
  1048. logically::
  1049. # Final result is that everything except "headline" is deferred.
  1050. Entry.objects.only("headline", "body").defer("body")
  1051. # Final result loads headline and body immediately (only() replaces any
  1052. # existing set of fields).
  1053. Entry.objects.defer("body").only("headline", "body")
  1054. All of the cautions in the note for the :meth:`defer` documentation apply to
  1055. ``only()`` as well. Use it cautiously and only after exhausting your other
  1056. options.
  1057. Using :meth:`only` and omitting a field requested using :meth:`select_related`
  1058. is an error as well.
  1059. .. note::
  1060. When calling :meth:`~django.db.models.Model.save()` for instances with
  1061. deferred fields, only the loaded fields will be saved. See
  1062. :meth:`~django.db.models.Model.save()` for more details.
  1063. using
  1064. ~~~~~
  1065. .. method:: using(alias)
  1066. This method is for controlling which database the ``QuerySet`` will be
  1067. evaluated against if you are using more than one database. The only argument
  1068. this method takes is the alias of a database, as defined in
  1069. :setting:`DATABASES`.
  1070. For example::
  1071. # queries the database with the 'default' alias.
  1072. >>> Entry.objects.all()
  1073. # queries the database with the 'backup' alias
  1074. >>> Entry.objects.using('backup')
  1075. select_for_update
  1076. ~~~~~~~~~~~~~~~~~
  1077. .. method:: select_for_update(nowait=False)
  1078. Returns a queryset that will lock rows until the end of the transaction,
  1079. generating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases.
  1080. For example::
  1081. entries = Entry.objects.select_for_update().filter(author=request.user)
  1082. All matched entries will be locked until the end of the transaction block,
  1083. meaning that other transactions will be prevented from changing or acquiring
  1084. locks on them.
  1085. Usually, if another transaction has already acquired a lock on one of the
  1086. selected rows, the query will block until the lock is released. If this is
  1087. not the behavior you want, call ``select_for_update(nowait=True)``. This will
  1088. make the call non-blocking. If a conflicting lock is already acquired by
  1089. another transaction, :exc:`~django.db.DatabaseError` will be raised when the
  1090. queryset is evaluated.
  1091. Currently, the ``postgresql_psycopg2``, ``oracle``, and ``mysql`` database
  1092. backends support ``select_for_update()``. However, MySQL has no support for the
  1093. ``nowait`` argument. Obviously, users of external third-party backends should
  1094. check with their backend's documentation for specifics in those cases.
  1095. Passing ``nowait=True`` to ``select_for_update()`` using database backends that
  1096. do not support ``nowait``, such as MySQL, will cause a
  1097. :exc:`~django.db.DatabaseError` to be raised. This is in order to prevent code
  1098. unexpectedly blocking.
  1099. Evaluating a queryset with ``select_for_update()`` in autocommit mode on
  1100. backends which support ``SELECT ... FOR UPDATE`` is a
  1101. :exc:`~django.db.transaction.TransactionManagementError` error because the
  1102. rows are not locked in that case. If allowed, this would facilitate data
  1103. corruption and could easily be caused by calling code that expects to be run in
  1104. a transaction outside of one.
  1105. Using ``select_for_update()`` on backends which do not support
  1106. ``SELECT ... FOR UPDATE`` (such as SQLite) will have no effect.
  1107. ``SELECT ... FOR UPDATE`` will not be added to the query, and an error isn't
  1108. raised if ``select_for_update()`` is used in autocommit mode.
  1109. .. warning::
  1110. Although ``select_for_update()`` normally fails in autocommit mode, since
  1111. :class:`~django.test.TestCase` automatically wraps each test in a
  1112. transaction, calling ``select_for_update()`` in a ``TestCase`` even outside
  1113. an :func:`~django.db.transaction.atomic()` block will (perhaps unexpectedly)
  1114. pass without raising a ``TransactionManagementError``. To properly test
  1115. ``select_for_update()`` you should use
  1116. :class:`~django.test.TransactionTestCase`.
  1117. raw
  1118. ~~~
  1119. .. method:: raw(raw_query, params=None, translations=None)
  1120. Takes a raw SQL query, executes it, and returns a
  1121. ``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
  1122. can be iterated over just like an normal ``QuerySet`` to provide object instances.
  1123. See the :doc:`/topics/db/sql` for more information.
  1124. .. warning::
  1125. ``raw()`` always triggers a new query and doesn't account for previous
  1126. filtering. As such, it should generally be called from the ``Manager`` or
  1127. from a fresh ``QuerySet`` instance.
  1128. Methods that do not return QuerySets
  1129. ------------------------------------
  1130. The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
  1131. something *other than* a ``QuerySet``.
  1132. These methods do not use a cache (see :ref:`caching-and-querysets`). Rather,
  1133. they query the database each time they're called.
  1134. get
  1135. ~~~
  1136. .. method:: get(**kwargs)
  1137. Returns the object matching the given lookup parameters, which should be in
  1138. the format described in `Field lookups`_.
  1139. ``get()`` raises :exc:`~django.core.exceptions.MultipleObjectsReturned` if more
  1140. than one object was found. The
  1141. :exc:`~django.core.exceptions.MultipleObjectsReturned` exception is an
  1142. attribute of the model class.
  1143. ``get()`` raises a :exc:`~django.db.models.Model.DoesNotExist` exception if an
  1144. object wasn't found for the given parameters. This exception is an attribute
  1145. of the model class. Example::
  1146. Entry.objects.get(id='foo') # raises Entry.DoesNotExist
  1147. The :exc:`~django.db.models.Model.DoesNotExist` exception inherits from
  1148. :exc:`django.core.exceptions.ObjectDoesNotExist`, so you can target multiple
  1149. :exc:`~django.db.models.Model.DoesNotExist` exceptions. Example::
  1150. from django.core.exceptions import ObjectDoesNotExist
  1151. try:
  1152. e = Entry.objects.get(id=3)
  1153. b = Blog.objects.get(id=1)
  1154. except ObjectDoesNotExist:
  1155. print("Either the entry or blog doesn't exist.")
  1156. create
  1157. ~~~~~~
  1158. .. method:: create(**kwargs)
  1159. A convenience method for creating an object and saving it all in one step. Thus::
  1160. p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
  1161. and::
  1162. p = Person(first_name="Bruce", last_name="Springsteen")
  1163. p.save(force_insert=True)
  1164. are equivalent.
  1165. The :ref:`force_insert <ref-models-force-insert>` parameter is documented
  1166. elsewhere, but all it means is that a new object will always be created.
  1167. Normally you won't need to worry about this. However, if your model contains a
  1168. manual primary key value that you set and if that value already exists in the
  1169. database, a call to ``create()`` will fail with an
  1170. :exc:`~django.db.IntegrityError` since primary keys must be unique. Be
  1171. prepared to handle the exception if you are using manual primary keys.
  1172. get_or_create
  1173. ~~~~~~~~~~~~~
  1174. .. method:: get_or_create(defaults=None, **kwargs)
  1175. A convenience method for looking up an object with the given ``kwargs`` (may be
  1176. empty if your model has defaults for all fields), creating one if necessary.
  1177. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
  1178. created object and ``created`` is a boolean specifying whether a new object was
  1179. created.
  1180. This is meant as a shortcut to boilerplatish code. For example::
  1181. try:
  1182. obj = Person.objects.get(first_name='John', last_name='Lennon')
  1183. except Person.DoesNotExist:
  1184. obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
  1185. obj.save()
  1186. This pattern gets quite unwieldy as the number of fields in a model goes up.
  1187. The above example can be rewritten using ``get_or_create()`` like so::
  1188. obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
  1189. defaults={'birthday': date(1940, 10, 9)})
  1190. Any keyword arguments passed to ``get_or_create()`` — *except* an optional one
  1191. called ``defaults`` — will be used in a :meth:`get()` call. If an object is
  1192. found, ``get_or_create()`` returns a tuple of that object and ``False``. If
  1193. multiple objects are found, ``get_or_create`` raises
  1194. :exc:`~django.core.exceptions.MultipleObjectsReturned`. If an object is *not*
  1195. found, ``get_or_create()`` will instantiate and save a new object, returning a
  1196. tuple of the new object and ``True``. The new object will be created roughly
  1197. according to this algorithm::
  1198. params = {k: v for k, v in kwargs.items() if '__' not in k}
  1199. params.update(defaults)
  1200. obj = self.model(**params)
  1201. obj.save()
  1202. In English, that means start with any non-``'defaults'`` keyword argument that
  1203. doesn't contain a double underscore (which would indicate a non-exact lookup).
  1204. Then add the contents of ``defaults``, overriding any keys if necessary, and
  1205. use the result as the keyword arguments to the model class. As hinted at
  1206. above, this is a simplification of the algorithm that is used, but it contains
  1207. all the pertinent details. The internal implementation has some more
  1208. error-checking than this and handles some extra edge-conditions; if you're
  1209. interested, read the code.
  1210. If you have a field named ``defaults`` and want to use it as an exact lookup in
  1211. ``get_or_create()``, just use ``'defaults__exact'``, like so::
  1212. Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
  1213. The ``get_or_create()`` method has similar error behavior to :meth:`create()`
  1214. when you're using manually specified primary keys. If an object needs to be
  1215. created and the key already exists in the database, an
  1216. :exc:`~django.db.IntegrityError` will be raised.
  1217. This method is atomic assuming correct usage, correct database configuration,
  1218. and correct behavior of the underlying database. However, if uniqueness is not
  1219. enforced at the database level for the ``kwargs`` used in a ``get_or_create``
  1220. call (see :attr:`~django.db.models.Field.unique` or
  1221. :attr:`~django.db.models.Options.unique_together`), this method is prone to a
  1222. race-condition which can result in multiple rows with the same parameters being
  1223. inserted simultaneously.
  1224. If you are using MySQL, be sure to use the ``READ COMMITTED`` isolation level
  1225. rather than ``REPEATABLE READ`` (the default), otherwise you may see cases
  1226. where ``get_or_create`` will raise an :exc:`~django.db.IntegrityError` but the
  1227. object won't appear in a subsequent :meth:`~django.db.models.query.QuerySet.get`
  1228. call.
  1229. Finally, a word on using ``get_or_create()`` in Django views. Please make sure
  1230. to use it only in ``POST`` requests unless you have a good reason not to.
  1231. ``GET`` requests shouldn't have any effect on data. Instead, use ``POST``
  1232. whenever a request to a page has a side effect on your data. For more, see
  1233. `Safe methods`_ in the HTTP spec.
  1234. .. _Safe methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
  1235. .. warning::
  1236. You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`
  1237. attributes and reverse relations. In that case you will restrict the queries
  1238. inside the context of that relation. That could lead you to some integrity
  1239. problems if you don't use it consistently.
  1240. Being the following models::
  1241. class Chapter(models.Model):
  1242. title = models.CharField(max_length=255, unique=True)
  1243. class Book(models.Model):
  1244. title = models.CharField(max_length=256)
  1245. chapters = models.ManyToManyField(Chapter)
  1246. You can use ``get_or_create()`` through Book's chapters field, but it only
  1247. fetches inside the context of that book::
  1248. >>> book = Book.objects.create(title="Ulysses")
  1249. >>> book.chapters.get_or_create(title="Telemachus")
  1250. (<Chapter: Telemachus>, True)
  1251. >>> book.chapters.get_or_create(title="Telemachus")
  1252. (<Chapter: Telemachus>, False)
  1253. >>> Chapter.objects.create(title="Chapter 1")
  1254. <Chapter: Chapter 1>
  1255. >>> book.chapters.get_or_create(title="Chapter 1")
  1256. # Raises IntegrityError
  1257. This is happening because it's trying to get or create "Chapter 1" through the
  1258. book "Ulysses", but it can't do any of them: the relation can't fetch that
  1259. chapter because it isn't related to that book, but it can't create it either
  1260. because ``title`` field should be unique.
  1261. update_or_create
  1262. ~~~~~~~~~~~~~~~~
  1263. .. method:: update_or_create(defaults=None, **kwargs)
  1264. A convenience method for updating an object with the given ``kwargs``, creating
  1265. a new one if necessary. The ``defaults`` is a dictionary of (field, value)
  1266. pairs used to update the object.
  1267. Returns a tuple of ``(object, created)``, where ``object`` is the created or
  1268. updated object and ``created`` is a boolean specifying whether a new object was
  1269. created.
  1270. The ``update_or_create`` method tries to fetch an object from database based on
  1271. the given ``kwargs``. If a match is found, it updates the fields passed in the
  1272. ``defaults`` dictionary.
  1273. This is meant as a shortcut to boilerplatish code. For example::
  1274. try:
  1275. obj = Person.objects.get(first_name='John', last_name='Lennon')
  1276. for key, value in updated_values.iteritems():
  1277. setattr(obj, key, value)
  1278. obj.save()
  1279. except Person.DoesNotExist:
  1280. updated_values.update({'first_name': 'John', 'last_name': 'Lennon'})
  1281. obj = Person(**updated_values)
  1282. obj.save()
  1283. This pattern gets quite unwieldy as the number of fields in a model goes up.
  1284. The above example can be rewritten using ``update_or_create()`` like so::
  1285. obj, created = Person.objects.update_or_create(
  1286. first_name='John', last_name='Lennon', defaults=updated_values)
  1287. For detailed description how names passed in ``kwargs`` are resolved see
  1288. :meth:`get_or_create`.
  1289. As described above in :meth:`get_or_create`, this method is prone to a
  1290. race-condition which can result in multiple rows being inserted simultaneously
  1291. if uniqueness is not enforced at the database level.
  1292. bulk_create
  1293. ~~~~~~~~~~~
  1294. .. method:: bulk_create(objs, batch_size=None)
  1295. This method inserts the provided list of objects into the database in an
  1296. efficient manner (generally only 1 query, no matter how many objects there
  1297. are)::
  1298. >>> Entry.objects.bulk_create([
  1299. ... Entry(headline="Django 1.0 Released"),
  1300. ... Entry(headline="Django 1.1 Announced"),
  1301. ... Entry(headline="Breaking: Django is awesome")
  1302. ... ])
  1303. This has a number of caveats though:
  1304. * The model's ``save()`` method will not be called, and the ``pre_save`` and
  1305. ``post_save`` signals will not be sent.
  1306. * It does not work with child models in a multi-table inheritance scenario.
  1307. * If the model's primary key is an :class:`~django.db.models.AutoField` it
  1308. does not retrieve and set the primary key attribute, as ``save()`` does.
  1309. * It does not work with many-to-many relationships.
  1310. .. versionchanged:: 1.9
  1311. Support for using ``bulk_create()`` with proxy models was added.
  1312. The ``batch_size`` parameter controls how many objects are created in single
  1313. query. The default is to create all objects in one batch, except for SQLite
  1314. where the default is such that at most 999 variables per query are used.
  1315. count
  1316. ~~~~~
  1317. .. method:: count()
  1318. Returns an integer representing the number of objects in the database matching
  1319. the ``QuerySet``. The ``count()`` method never raises exceptions.
  1320. Example::
  1321. # Returns the total number of entries in the database.
  1322. Entry.objects.count()
  1323. # Returns the number of entries whose headline contains 'Lennon'
  1324. Entry.objects.filter(headline__contains='Lennon').count()
  1325. A ``count()`` call performs a ``SELECT COUNT(*)`` behind the scenes, so you
  1326. should always use ``count()`` rather than loading all of the record into Python
  1327. objects and calling ``len()`` on the result (unless you need to load the
  1328. objects into memory anyway, in which case ``len()`` will be faster).
  1329. Depending on which database you're using (e.g. PostgreSQL vs. MySQL),
  1330. ``count()`` may return a long integer instead of a normal Python integer. This
  1331. is an underlying implementation quirk that shouldn't pose any real-world
  1332. problems.
  1333. Note that if you want the number of items in a ``QuerySet`` and are also
  1334. retrieving model instances from it (for example, by iterating over it), it's
  1335. probably more efficient to use ``len(queryset)`` which won't cause an extra
  1336. database query like ``count()`` would.
  1337. in_bulk
  1338. ~~~~~~~
  1339. .. method:: in_bulk(id_list)
  1340. Takes a list of primary-key values and returns a dictionary mapping each
  1341. primary-key value to an instance of the object with the given ID.
  1342. Example::
  1343. >>> Blog.objects.in_bulk([1])
  1344. {1: <Blog: Beatles Blog>}
  1345. >>> Blog.objects.in_bulk([1, 2])
  1346. {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
  1347. >>> Blog.objects.in_bulk([])
  1348. {}
  1349. If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
  1350. iterator
  1351. ~~~~~~~~
  1352. .. method:: iterator()
  1353. Evaluates the ``QuerySet`` (by performing the query) and returns an iterator
  1354. (see :pep:`234`) over the results. A ``QuerySet`` typically caches its results
  1355. internally so that repeated evaluations do not result in additional queries. In
  1356. contrast, ``iterator()`` will read results directly, without doing any caching
  1357. at the ``QuerySet`` level (internally, the default iterator calls ``iterator()``
  1358. and caches the return value). For a ``QuerySet`` which returns a large number of
  1359. objects that you only need to access once, this can result in better
  1360. performance and a significant reduction in memory.
  1361. Note that using ``iterator()`` on a ``QuerySet`` which has already been
  1362. evaluated will force it to evaluate again, repeating the query.
  1363. Also, use of ``iterator()`` causes previous ``prefetch_related()`` calls to be
  1364. ignored since these two optimizations do not make sense together.
  1365. .. warning::
  1366. Some Python database drivers like ``psycopg2`` perform caching if using
  1367. client side cursors (instantiated with ``connection.cursor()`` and what
  1368. Django's ORM uses). Using ``iterator()`` does not affect caching at the
  1369. database driver level. To disable this caching, look at `server side
  1370. cursors`_.
  1371. .. _server side cursors: http://initd.org/psycopg/docs/usage.html#server-side-cursors
  1372. latest
  1373. ~~~~~~
  1374. .. method:: latest(field_name=None)
  1375. Returns the latest object in the table, by date, using the ``field_name``
  1376. provided as the date field.
  1377. This example returns the latest ``Entry`` in the table, according to the
  1378. ``pub_date`` field::
  1379. Entry.objects.latest('pub_date')
  1380. If your model's :ref:`Meta <meta-options>` specifies
  1381. :attr:`~django.db.models.Options.get_latest_by`, you can leave off the
  1382. ``field_name`` argument to ``earliest()`` or ``latest()``. Django will use the
  1383. field specified in :attr:`~django.db.models.Options.get_latest_by` by default.
  1384. Like :meth:`get()`, ``earliest()`` and ``latest()`` raise
  1385. :exc:`~django.db.models.Model.DoesNotExist` if there is no object with the
  1386. given parameters.
  1387. Note that ``earliest()`` and ``latest()`` exist purely for convenience and
  1388. readability.
  1389. earliest
  1390. ~~~~~~~~
  1391. .. method:: earliest(field_name=None)
  1392. Works otherwise like :meth:`~django.db.models.query.QuerySet.latest` except
  1393. the direction is changed.
  1394. first
  1395. ~~~~~
  1396. .. method:: first()
  1397. Returns the first object matched by the queryset, or ``None`` if there
  1398. is no matching object. If the ``QuerySet`` has no ordering defined, then the
  1399. queryset is automatically ordered by the primary key.
  1400. Example::
  1401. p = Article.objects.order_by('title', 'pub_date').first()
  1402. Note that ``first()`` is a convenience method, the following code sample is
  1403. equivalent to the above example::
  1404. try:
  1405. p = Article.objects.order_by('title', 'pub_date')[0]
  1406. except IndexError:
  1407. p = None
  1408. last
  1409. ~~~~
  1410. .. method:: last()
  1411. Works like :meth:`first()`, but returns the last object in the queryset.
  1412. aggregate
  1413. ~~~~~~~~~
  1414. .. method:: aggregate(*args, **kwargs)
  1415. Returns a dictionary of aggregate values (averages, sums, etc) calculated over
  1416. the ``QuerySet``. Each argument to ``aggregate()`` specifies a value that will
  1417. be included in the dictionary that is returned.
  1418. The aggregation functions that are provided by Django are described in
  1419. `Aggregation Functions`_ below. Since aggregates are also :doc:`query
  1420. expressions </ref/models/expressions>`, you may combine aggregates with other
  1421. aggregates or values to create complex aggregates.
  1422. Aggregates specified using keyword arguments will use the keyword as the name
  1423. for the annotation. Anonymous arguments will have a name generated for them
  1424. based upon the name of the aggregate function and the model field that is being
  1425. aggregated. Complex aggregates cannot use anonymous arguments and must specify
  1426. a keyword argument as an alias.
  1427. For example, when you are working with blog entries, you may want to know the
  1428. number of authors that have contributed blog entries::
  1429. >>> from django.db.models import Count
  1430. >>> q = Blog.objects.aggregate(Count('entry'))
  1431. {'entry__count': 16}
  1432. By using a keyword argument to specify the aggregate function, you can
  1433. control the name of the aggregation value that is returned::
  1434. >>> q = Blog.objects.aggregate(number_of_entries=Count('entry'))
  1435. {'number_of_entries': 16}
  1436. For an in-depth discussion of aggregation, see :doc:`the topic guide on
  1437. Aggregation </topics/db/aggregation>`.
  1438. exists
  1439. ~~~~~~
  1440. .. method:: exists()
  1441. Returns ``True`` if the :class:`.QuerySet` contains any results, and ``False``
  1442. if not. This tries to perform the query in the simplest and fastest way
  1443. possible, but it *does* execute nearly the same query as a normal
  1444. :class:`.QuerySet` query.
  1445. :meth:`~.QuerySet.exists` is useful for searches relating to both
  1446. object membership in a :class:`.QuerySet` and to the existence of any objects in
  1447. a :class:`.QuerySet`, particularly in the context of a large :class:`.QuerySet`.
  1448. The most efficient method of finding whether a model with a unique field
  1449. (e.g. ``primary_key``) is a member of a :class:`.QuerySet` is::
  1450. entry = Entry.objects.get(pk=123)
  1451. if some_queryset.filter(pk=entry.pk).exists():
  1452. print("Entry contained in queryset")
  1453. Which will be faster than the following which requires evaluating and iterating
  1454. through the entire queryset::
  1455. if entry in some_queryset:
  1456. print("Entry contained in QuerySet")
  1457. And to find whether a queryset contains any items::
  1458. if some_queryset.exists():
  1459. print("There is at least one object in some_queryset")
  1460. Which will be faster than::
  1461. if some_queryset:
  1462. print("There is at least one object in some_queryset")
  1463. ... but not by a large degree (hence needing a large queryset for efficiency
  1464. gains).
  1465. Additionally, if a ``some_queryset`` has not yet been evaluated, but you know
  1466. that it will be at some point, then using ``some_queryset.exists()`` will do
  1467. more overall work (one query for the existence check plus an extra one to later
  1468. retrieve the results) than simply using ``bool(some_queryset)``, which
  1469. retrieves the results and then checks if any were returned.
  1470. update
  1471. ~~~~~~
  1472. .. method:: update(**kwargs)
  1473. Performs an SQL update query for the specified fields, and returns
  1474. the number of rows matched (which may not be equal to the number of rows
  1475. updated if some rows already have the new value).
  1476. For example, to turn comments off for all blog entries published in 2010,
  1477. you could do this::
  1478. >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
  1479. (This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.)
  1480. You can update multiple fields — there's no limit on how many. For example,
  1481. here we update the ``comments_on`` and ``headline`` fields::
  1482. >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False, headline='This is old')
  1483. The ``update()`` method is applied instantly, and the only restriction on the
  1484. :class:`.QuerySet` that is updated is that it can only update columns in the
  1485. model's main table, not on related models. You can't do this, for example::
  1486. >>> Entry.objects.update(blog__name='foo') # Won't work!
  1487. Filtering based on related fields is still possible, though::
  1488. >>> Entry.objects.filter(blog__id=1).update(comments_on=True)
  1489. You cannot call ``update()`` on a :class:`.QuerySet` that has had a slice taken
  1490. or can otherwise no longer be filtered.
  1491. The ``update()`` method returns the number of affected rows::
  1492. >>> Entry.objects.filter(id=64).update(comments_on=True)
  1493. 1
  1494. >>> Entry.objects.filter(slug='nonexistent-slug').update(comments_on=True)
  1495. 0
  1496. >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
  1497. 132
  1498. If you're just updating a record and don't need to do anything with the model
  1499. object, the most efficient approach is to call ``update()``, rather than
  1500. loading the model object into memory. For example, instead of doing this::
  1501. e = Entry.objects.get(id=10)
  1502. e.comments_on = False
  1503. e.save()
  1504. ...do this::
  1505. Entry.objects.filter(id=10).update(comments_on=False)
  1506. Using ``update()`` also prevents a race condition wherein something might
  1507. change in your database in the short period of time between loading the object
  1508. and calling ``save()``.
  1509. Finally, realize that ``update()`` does an update at the SQL level and, thus,
  1510. does not call any ``save()`` methods on your models, nor does it emit the
  1511. :attr:`~django.db.models.signals.pre_save` or
  1512. :attr:`~django.db.models.signals.post_save` signals (which are a consequence of
  1513. calling :meth:`Model.save() <django.db.models.Model.save>`). If you want to
  1514. update a bunch of records for a model that has a custom
  1515. :meth:`~django.db.models.Model.save()` method, loop over them and call
  1516. :meth:`~django.db.models.Model.save()`, like this::
  1517. for e in Entry.objects.filter(pub_date__year=2010):
  1518. e.comments_on = False
  1519. e.save()
  1520. delete
  1521. ~~~~~~
  1522. .. method:: delete()
  1523. Performs an SQL delete query on all rows in the :class:`.QuerySet` and
  1524. returns the number of objects deleted and a dictionary with the number of
  1525. deletions per object type.
  1526. The ``delete()`` is applied instantly. You cannot call ``delete()`` on a
  1527. :class:`.QuerySet` that has had a slice taken or can otherwise no longer be
  1528. filtered.
  1529. For example, to delete all the entries in a particular blog::
  1530. >>> b = Blog.objects.get(pk=1)
  1531. # Delete all the entries belonging to this Blog.
  1532. >>> Entry.objects.filter(blog=b).delete()
  1533. (4, {'weblog.Entry': 2, 'weblog.Entry_authors': 2})
  1534. .. versionchanged:: 1.9
  1535. The return value describing the number of objects deleted was added.
  1536. By default, Django's :class:`~django.db.models.ForeignKey` emulates the SQL
  1537. constraint ``ON DELETE CASCADE`` — in other words, any objects with foreign
  1538. keys pointing at the objects to be deleted will be deleted along with them.
  1539. For example::
  1540. >>> blogs = Blog.objects.all()
  1541. # This will delete all Blogs and all of their Entry objects.
  1542. >>> blogs.delete()
  1543. (5, {'weblog.Blog': 1, 'weblog.Entry': 2, 'weblog.Entry_authors': 2})
  1544. This cascade behavior is customizable via the
  1545. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  1546. :class:`~django.db.models.ForeignKey`.
  1547. The ``delete()`` method does a bulk delete and does not call any ``delete()``
  1548. methods on your models. It does, however, emit the
  1549. :data:`~django.db.models.signals.pre_delete` and
  1550. :data:`~django.db.models.signals.post_delete` signals for all deleted objects
  1551. (including cascaded deletions).
  1552. Django needs to fetch objects into memory to send signals and handle cascades.
  1553. However, if there are no cascades and no signals, then Django may take a
  1554. fast-path and delete objects without fetching into memory. For large
  1555. deletes this can result in significantly reduced memory usage. The amount of
  1556. executed queries can be reduced, too.
  1557. ForeignKeys which are set to :attr:`~django.db.models.ForeignKey.on_delete`
  1558. ``DO_NOTHING`` do not prevent taking the fast-path in deletion.
  1559. Note that the queries generated in object deletion is an implementation
  1560. detail subject to change.
  1561. as_manager
  1562. ~~~~~~~~~~
  1563. .. classmethod:: as_manager()
  1564. Class method that returns an instance of :class:`~django.db.models.Manager`
  1565. with a copy of the ``QuerySet``’s methods. See
  1566. :ref:`create-manager-with-queryset-methods` for more details.
  1567. .. _field-lookups:
  1568. Field lookups
  1569. -------------
  1570. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
  1571. specified as keyword arguments to the ``QuerySet`` methods :meth:`filter()`,
  1572. :meth:`exclude()` and :meth:`get()`.
  1573. For an introduction, see :ref:`models and database queries documentation
  1574. <field-lookups-intro>`.
  1575. Django's inbuilt lookups are listed below. It is also possible to write
  1576. :doc:`custom lookups </howto/custom-lookups>` for model fields.
  1577. As a convenience when no lookup type is provided (like in
  1578. ``Entry.objects.get(id=14)``) the lookup type is assumed to be :lookup:`exact`.
  1579. .. fieldlookup:: exact
  1580. exact
  1581. ~~~~~
  1582. Exact match. If the value provided for comparison is ``None``, it will be
  1583. interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more details).
  1584. Examples::
  1585. Entry.objects.get(id__exact=14)
  1586. Entry.objects.get(id__exact=None)
  1587. SQL equivalents::
  1588. SELECT ... WHERE id = 14;
  1589. SELECT ... WHERE id IS NULL;
  1590. .. admonition:: MySQL comparisons
  1591. In MySQL, a database table's "collation" setting determines whether
  1592. ``exact`` comparisons are case-sensitive. This is a database setting, *not*
  1593. a Django setting. It's possible to configure your MySQL tables to use
  1594. case-sensitive comparisons, but some trade-offs are involved. For more
  1595. information about this, see the :ref:`collation section <mysql-collation>`
  1596. in the :doc:`databases </ref/databases>` documentation.
  1597. .. fieldlookup:: iexact
  1598. iexact
  1599. ~~~~~~
  1600. Case-insensitive exact match. If the value provided for comparison is ``None``,
  1601. it will be interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more
  1602. details).
  1603. Example::
  1604. Blog.objects.get(name__iexact='beatles blog')
  1605. Blog.objects.get(name__iexact=None)
  1606. SQL equivalents::
  1607. SELECT ... WHERE name ILIKE 'beatles blog';
  1608. SELECT ... WHERE name IS NULL;
  1609. Note the first query will match ``'Beatles Blog'``, ``'beatles blog'``,
  1610. ``'BeAtLes BLoG'``, etc.
  1611. .. admonition:: SQLite users
  1612. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  1613. mind the :ref:`database note <sqlite-string-matching>` about string
  1614. comparisons. SQLite does not do case-insensitive matching for Unicode
  1615. strings.
  1616. .. fieldlookup:: contains
  1617. contains
  1618. ~~~~~~~~
  1619. Case-sensitive containment test.
  1620. Example::
  1621. Entry.objects.get(headline__contains='Lennon')
  1622. SQL equivalent::
  1623. SELECT ... WHERE headline LIKE '%Lennon%';
  1624. Note this will match the headline ``'Lennon honored today'`` but not ``'lennon
  1625. honored today'``.
  1626. .. admonition:: SQLite users
  1627. SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains``
  1628. acts like ``icontains`` for SQLite. See the :ref:`database note
  1629. <sqlite-string-matching>` for more information.
  1630. .. fieldlookup:: icontains
  1631. icontains
  1632. ~~~~~~~~~
  1633. Case-insensitive containment test.
  1634. Example::
  1635. Entry.objects.get(headline__icontains='Lennon')
  1636. SQL equivalent::
  1637. SELECT ... WHERE headline ILIKE '%Lennon%';
  1638. .. admonition:: SQLite users
  1639. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  1640. mind the :ref:`database note <sqlite-string-matching>` about string
  1641. comparisons.
  1642. .. fieldlookup:: in
  1643. in
  1644. ~~
  1645. In a given list.
  1646. Example::
  1647. Entry.objects.filter(id__in=[1, 3, 4])
  1648. SQL equivalent::
  1649. SELECT ... WHERE id IN (1, 3, 4);
  1650. You can also use a queryset to dynamically evaluate the list of values
  1651. instead of providing a list of literal values::
  1652. inner_qs = Blog.objects.filter(name__contains='Cheddar')
  1653. entries = Entry.objects.filter(blog__in=inner_qs)
  1654. This queryset will be evaluated as subselect statement::
  1655. SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')
  1656. If you pass in a ``QuerySet`` resulting from ``values()`` or ``values_list()``
  1657. as the value to an ``__in`` lookup, you need to ensure you are only extracting
  1658. one field in the result. For example, this will work (filtering on the blog
  1659. names)::
  1660. inner_qs = Blog.objects.filter(name__contains='Ch').values('name')
  1661. entries = Entry.objects.filter(blog__name__in=inner_qs)
  1662. This example will raise an exception, since the inner query is trying to
  1663. extract two field values, where only one is expected::
  1664. # Bad code! Will raise a TypeError.
  1665. inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id')
  1666. entries = Entry.objects.filter(blog__name__in=inner_qs)
  1667. .. _nested-queries-performance:
  1668. .. admonition:: Performance considerations
  1669. Be cautious about using nested queries and understand your database
  1670. server's performance characteristics (if in doubt, benchmark!). Some
  1671. database backends, most notably MySQL, don't optimize nested queries very
  1672. well. It is more efficient, in those cases, to extract a list of values
  1673. and then pass that into the second query. That is, execute two queries
  1674. instead of one::
  1675. values = Blog.objects.filter(
  1676. name__contains='Cheddar').values_list('pk', flat=True)
  1677. entries = Entry.objects.filter(blog__in=list(values))
  1678. Note the ``list()`` call around the Blog ``QuerySet`` to force execution of
  1679. the first query. Without it, a nested query would be executed, because
  1680. :ref:`querysets-are-lazy`.
  1681. .. fieldlookup:: gt
  1682. gt
  1683. ~~
  1684. Greater than.
  1685. Example::
  1686. Entry.objects.filter(id__gt=4)
  1687. SQL equivalent::
  1688. SELECT ... WHERE id > 4;
  1689. .. fieldlookup:: gte
  1690. gte
  1691. ~~~
  1692. Greater than or equal to.
  1693. .. fieldlookup:: lt
  1694. lt
  1695. ~~
  1696. Less than.
  1697. .. fieldlookup:: lte
  1698. lte
  1699. ~~~
  1700. Less than or equal to.
  1701. .. fieldlookup:: startswith
  1702. startswith
  1703. ~~~~~~~~~~
  1704. Case-sensitive starts-with.
  1705. Example::
  1706. Entry.objects.filter(headline__startswith='Will')
  1707. SQL equivalent::
  1708. SELECT ... WHERE headline LIKE 'Will%';
  1709. SQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts
  1710. like ``istartswith`` for SQLite.
  1711. .. fieldlookup:: istartswith
  1712. istartswith
  1713. ~~~~~~~~~~~
  1714. Case-insensitive starts-with.
  1715. Example::
  1716. Entry.objects.filter(headline__istartswith='will')
  1717. SQL equivalent::
  1718. SELECT ... WHERE headline ILIKE 'Will%';
  1719. .. admonition:: SQLite users
  1720. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  1721. mind the :ref:`database note <sqlite-string-matching>` about string
  1722. comparisons.
  1723. .. fieldlookup:: endswith
  1724. endswith
  1725. ~~~~~~~~
  1726. Case-sensitive ends-with.
  1727. Example::
  1728. Entry.objects.filter(headline__endswith='cats')
  1729. SQL equivalent::
  1730. SELECT ... WHERE headline LIKE '%cats';
  1731. .. admonition:: SQLite users
  1732. SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith``
  1733. acts like ``iendswith`` for SQLite. Refer to the :ref:`database note
  1734. <sqlite-string-matching>` documentation for more.
  1735. .. fieldlookup:: iendswith
  1736. iendswith
  1737. ~~~~~~~~~
  1738. Case-insensitive ends-with.
  1739. Example::
  1740. Entry.objects.filter(headline__iendswith='will')
  1741. SQL equivalent::
  1742. SELECT ... WHERE headline ILIKE '%will'
  1743. .. admonition:: SQLite users
  1744. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  1745. mind the :ref:`database note <sqlite-string-matching>` about string
  1746. comparisons.
  1747. .. fieldlookup:: range
  1748. range
  1749. ~~~~~
  1750. Range test (inclusive).
  1751. Example::
  1752. import datetime
  1753. start_date = datetime.date(2005, 1, 1)
  1754. end_date = datetime.date(2005, 3, 31)
  1755. Entry.objects.filter(pub_date__range=(start_date, end_date))
  1756. SQL equivalent::
  1757. SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
  1758. You can use ``range`` anywhere you can use ``BETWEEN`` in SQL — for dates,
  1759. numbers and even characters.
  1760. .. warning::
  1761. Filtering a ``DateTimeField`` with dates won't include items on the last
  1762. day, because the bounds are interpreted as "0am on the given date". If
  1763. ``pub_date`` was a ``DateTimeField``, the above expression would be turned
  1764. into this SQL::
  1765. SELECT ... WHERE pub_date BETWEEN '2005-01-01 00:00:00' and '2005-03-31 00:00:00';
  1766. Generally speaking, you can't mix dates and datetimes.
  1767. .. fieldlookup:: date
  1768. date
  1769. ~~~~
  1770. .. versionadded:: 1.9
  1771. For datetime fields, casts the value as date. Allows chaining additional field
  1772. lookups. Takes a date value.
  1773. Example::
  1774. Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
  1775. Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
  1776. (No equivalent SQL code fragment is included for this lookup because
  1777. implementation of the relevant query varies among different database engines.)
  1778. When :setting:`USE_TZ` is ``True``, fields are converted to the current time
  1779. zone before filtering.
  1780. .. fieldlookup:: year
  1781. year
  1782. ~~~~
  1783. For date and datetime fields, an exact year match. Allows chaining additional
  1784. field lookups. Takes an integer year.
  1785. Example::
  1786. Entry.objects.filter(pub_date__year=2005)
  1787. Entry.objects.filter(pub_date__year__gte=2005)
  1788. SQL equivalent::
  1789. SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31';
  1790. SELECT ... WHERE pub_date >= '2005-01-01';
  1791. (The exact SQL syntax varies for each database engine.)
  1792. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  1793. current time zone before filtering.
  1794. .. versionchanged:: 1.9
  1795. Allowed chaining additional field lookups.
  1796. .. fieldlookup:: month
  1797. month
  1798. ~~~~~
  1799. For date and datetime fields, an exact month match. Allows chaining additional
  1800. field lookups. Takes an integer 1 (January) through 12 (December).
  1801. Example::
  1802. Entry.objects.filter(pub_date__month=12)
  1803. Entry.objects.filter(pub_date__month__gte=6)
  1804. SQL equivalent::
  1805. SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
  1806. SELECT ... WHERE EXTRACT('month' FROM pub_date) >= '6';
  1807. (The exact SQL syntax varies for each database engine.)
  1808. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  1809. current time zone before filtering. This requires :ref:`time zone definitions
  1810. in the database <database-time-zone-definitions>`.
  1811. .. versionchanged:: 1.9
  1812. Allowed chaining additional field lookups.
  1813. .. fieldlookup:: day
  1814. day
  1815. ~~~
  1816. For date and datetime fields, an exact day match. Allows chaining additional
  1817. field lookups. Takes an integer day.
  1818. Example::
  1819. Entry.objects.filter(pub_date__day=3)
  1820. Entry.objects.filter(pub_date__day__gte=3)
  1821. SQL equivalent::
  1822. SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
  1823. SELECT ... WHERE EXTRACT('day' FROM pub_date) >= '3';
  1824. (The exact SQL syntax varies for each database engine.)
  1825. Note this will match any record with a pub_date on the third day of the month,
  1826. such as January 3, July 3, etc.
  1827. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  1828. current time zone before filtering. This requires :ref:`time zone definitions
  1829. in the database <database-time-zone-definitions>`.
  1830. .. versionchanged:: 1.9
  1831. Allowed chaining additional field lookups.
  1832. .. fieldlookup:: week_day
  1833. week_day
  1834. ~~~~~~~~
  1835. For date and datetime fields, a 'day of the week' match. Allows chaining
  1836. additional field lookups.
  1837. Takes an integer value representing the day of week from 1 (Sunday) to 7
  1838. (Saturday).
  1839. Example::
  1840. Entry.objects.filter(pub_date__week_day=2)
  1841. Entry.objects.filter(pub_date__week_day__gte=2)
  1842. (No equivalent SQL code fragment is included for this lookup because
  1843. implementation of the relevant query varies among different database engines.)
  1844. Note this will match any record with a ``pub_date`` that falls on a Monday (day
  1845. 2 of the week), regardless of the month or year in which it occurs. Week days
  1846. are indexed with day 1 being Sunday and day 7 being Saturday.
  1847. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  1848. current time zone before filtering. This requires :ref:`time zone definitions
  1849. in the database <database-time-zone-definitions>`.
  1850. .. versionchanged:: 1.9
  1851. Allowed chaining additional field lookups.
  1852. .. fieldlookup:: hour
  1853. hour
  1854. ~~~~
  1855. For datetime and time fields, an exact hour match. Allows chaining additional
  1856. field lookups. Takes an integer between 0 and 23.
  1857. Example::
  1858. Event.objects.filter(timestamp__hour=23)
  1859. Event.objects.filter(time__hour=5)
  1860. Event.objects.filter(timestamp__hour__gte=12)
  1861. SQL equivalent::
  1862. SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';
  1863. SELECT ... WHERE EXTRACT('hour' FROM time) = '5';
  1864. SELECT ... WHERE EXTRACT('hour' FROM timestamp) >= '12';
  1865. (The exact SQL syntax varies for each database engine.)
  1866. For datetime fields, when :setting:`USE_TZ` is ``True``, values are converted
  1867. to the current time zone before filtering.
  1868. .. versionchanged:: 1.9
  1869. Added support for :class:`~django.db.models.TimeField` on SQLite (other
  1870. databases supported it as of 1.7).
  1871. .. versionchanged:: 1.9
  1872. Allowed chaining additional field lookups.
  1873. .. fieldlookup:: minute
  1874. minute
  1875. ~~~~~~
  1876. For datetime and time fields, an exact minute match. Allows chaining additional
  1877. field lookups. Takes an integer between 0 and 59.
  1878. Example::
  1879. Event.objects.filter(timestamp__minute=29)
  1880. Event.objects.filter(time__minute=46)
  1881. Event.objects.filter(timestamp__minute__gte=29)
  1882. SQL equivalent::
  1883. SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';
  1884. SELECT ... WHERE EXTRACT('minute' FROM time) = '46';
  1885. SELECT ... WHERE EXTRACT('minute' FROM timestamp) >= '29';
  1886. (The exact SQL syntax varies for each database engine.)
  1887. For datetime fields, When :setting:`USE_TZ` is ``True``, values are converted
  1888. to the current time zone before filtering.
  1889. .. versionchanged:: 1.9
  1890. Added support for :class:`~django.db.models.TimeField` on SQLite (other
  1891. databases supported it as of 1.7).
  1892. .. versionchanged:: 1.9
  1893. Allowed chaining additional field lookups.
  1894. .. fieldlookup:: second
  1895. second
  1896. ~~~~~~
  1897. For datetime and time fields, an exact second match. Allows chaining additional
  1898. field lookups. Takes an integer between 0 and 59.
  1899. Example::
  1900. Event.objects.filter(timestamp__second=31)
  1901. Event.objects.filter(time__second=2)
  1902. Event.objects.filter(timestamp__second__gte=31)
  1903. SQL equivalent::
  1904. SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';
  1905. SELECT ... WHERE EXTRACT('second' FROM time) = '2';
  1906. SELECT ... WHERE EXTRACT('second' FROM timestamp) >= '31';
  1907. (The exact SQL syntax varies for each database engine.)
  1908. For datetime fields, when :setting:`USE_TZ` is ``True``, values are converted
  1909. to the current time zone before filtering.
  1910. .. versionchanged:: 1.9
  1911. Added support for :class:`~django.db.models.TimeField` on SQLite (other
  1912. databases supported it as of 1.7).
  1913. .. versionchanged:: 1.9
  1914. Allowed chaining additional field lookups.
  1915. .. fieldlookup:: isnull
  1916. isnull
  1917. ~~~~~~
  1918. Takes either ``True`` or ``False``, which correspond to SQL queries of
  1919. ``IS NULL`` and ``IS NOT NULL``, respectively.
  1920. Example::
  1921. Entry.objects.filter(pub_date__isnull=True)
  1922. SQL equivalent::
  1923. SELECT ... WHERE pub_date IS NULL;
  1924. .. fieldlookup:: search
  1925. search
  1926. ~~~~~~
  1927. A boolean full-text search, taking advantage of full-text indexing. This is
  1928. like :lookup:`contains` but is significantly faster due to full-text indexing.
  1929. Example::
  1930. Entry.objects.filter(headline__search="+Django -jazz Python")
  1931. SQL equivalent::
  1932. SELECT ... WHERE MATCH(tablename, headline) AGAINST (+Django -jazz Python IN BOOLEAN MODE);
  1933. Note this is only available in MySQL and requires direct manipulation of the
  1934. database to add the full-text index. By default Django uses BOOLEAN MODE for
  1935. full text searches. See the `MySQL documentation`_ for additional details.
  1936. .. _MySQL documentation: http://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html
  1937. .. fieldlookup:: regex
  1938. regex
  1939. ~~~~~
  1940. Case-sensitive regular expression match.
  1941. The regular expression syntax is that of the database backend in use.
  1942. In the case of SQLite, which has no built in regular expression support,
  1943. this feature is provided by a (Python) user-defined REGEXP function, and
  1944. the regular expression syntax is therefore that of Python's ``re`` module.
  1945. Example::
  1946. Entry.objects.get(title__regex=r'^(An?|The) +')
  1947. SQL equivalents::
  1948. SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL
  1949. SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'c'); -- Oracle
  1950. SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL
  1951. SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite
  1952. Using raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the
  1953. regular expression syntax is recommended.
  1954. .. fieldlookup:: iregex
  1955. iregex
  1956. ~~~~~~
  1957. Case-insensitive regular expression match.
  1958. Example::
  1959. Entry.objects.get(title__iregex=r'^(an?|the) +')
  1960. SQL equivalents::
  1961. SELECT ... WHERE title REGEXP '^(an?|the) +'; -- MySQL
  1962. SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'i'); -- Oracle
  1963. SELECT ... WHERE title ~* '^(an?|the) +'; -- PostgreSQL
  1964. SELECT ... WHERE title REGEXP '(?i)^(an?|the) +'; -- SQLite
  1965. .. _aggregation-functions:
  1966. Aggregation functions
  1967. ---------------------
  1968. .. currentmodule:: django.db.models
  1969. Django provides the following aggregation functions in the
  1970. ``django.db.models`` module. For details on how to use these
  1971. aggregate functions, see :doc:`the topic guide on aggregation
  1972. </topics/db/aggregation>`. See the :class:`~django.db.models.Aggregate`
  1973. documentation to learn how to create your aggregates.
  1974. .. warning::
  1975. SQLite can't handle aggregation on date/time fields out of the box.
  1976. This is because there are no native date/time fields in SQLite and Django
  1977. currently emulates these features using a text field. Attempts to use
  1978. aggregation on date/time fields in SQLite will raise
  1979. ``NotImplementedError``.
  1980. .. admonition:: Note
  1981. Aggregation functions return ``None`` when used with an empty
  1982. ``QuerySet``. For example, the ``Sum`` aggregation function returns ``None``
  1983. instead of ``0`` if the ``QuerySet`` contains no entries. An exception is
  1984. ``Count``, which does return ``0`` if the ``QuerySet`` is empty.
  1985. All aggregates have the following parameters in common:
  1986. ``expression``
  1987. ~~~~~~~~~~~~~~
  1988. A string that references a field on the model, or a :doc:`query expression
  1989. </ref/models/expressions>`.
  1990. .. versionadded:: 1.8
  1991. Aggregate functions are now able to reference multiple fields in complex
  1992. computations.
  1993. ``output_field``
  1994. ~~~~~~~~~~~~~~~~
  1995. An optional argument that represents the :doc:`model field </ref/models/fields>`
  1996. of the return value
  1997. .. versionadded:: 1.8
  1998. The ``output_field`` argument was added.
  1999. .. note::
  2000. When combining multiple field types, Django can only determine the
  2001. ``output_field`` if all fields are of the same type. Otherwise, you
  2002. must provide the ``output_field`` yourself.
  2003. ``**extra``
  2004. ~~~~~~~~~~~
  2005. Keyword arguments that can provide extra context for the SQL generated
  2006. by the aggregate.
  2007. Avg
  2008. ~~~
  2009. .. class:: Avg(expression, output_field=FloatField(), **extra)
  2010. Returns the mean value of the given expression, which must be numeric
  2011. unless you specify a different ``output_field``.
  2012. * Default alias: ``<field>__avg``
  2013. * Return type: ``float`` (or the type of whatever ``output_field`` is
  2014. specified)
  2015. .. versionchanged:: 1.9
  2016. The ``output_field`` parameter was added to allow aggregating over
  2017. non-numeric columns, such as ``DurationField``.
  2018. Count
  2019. ~~~~~
  2020. .. class:: Count(expression, distinct=False, **extra)
  2021. Returns the number of objects that are related through the provided
  2022. expression.
  2023. * Default alias: ``<field>__count``
  2024. * Return type: ``int``
  2025. Has one optional argument:
  2026. .. attribute:: distinct
  2027. If ``distinct=True``, the count will only include unique instances.
  2028. This is the SQL equivalent of ``COUNT(DISTINCT <field>)``. The default
  2029. value is ``False``.
  2030. Max
  2031. ~~~
  2032. .. class:: Max(expression, output_field=None, **extra)
  2033. Returns the maximum value of the given expression.
  2034. * Default alias: ``<field>__max``
  2035. * Return type: same as input field, or ``output_field`` if supplied
  2036. Min
  2037. ~~~
  2038. .. class:: Min(expression, output_field=None, **extra)
  2039. Returns the minimum value of the given expression.
  2040. * Default alias: ``<field>__min``
  2041. * Return type: same as input field, or ``output_field`` if supplied
  2042. StdDev
  2043. ~~~~~~
  2044. .. class:: StdDev(expression, sample=False, **extra)
  2045. Returns the standard deviation of the data in the provided expression.
  2046. * Default alias: ``<field>__stddev``
  2047. * Return type: ``float``
  2048. Has one optional argument:
  2049. .. attribute:: sample
  2050. By default, ``StdDev`` returns the population standard deviation. However,
  2051. if ``sample=True``, the return value will be the sample standard deviation.
  2052. .. admonition:: SQLite
  2053. SQLite doesn't provide ``StdDev`` out of the box. An implementation
  2054. is available as an extension module for SQLite. Consult the `SQlite
  2055. documentation`_ for instructions on obtaining and installing this
  2056. extension.
  2057. Sum
  2058. ~~~
  2059. .. class:: Sum(expression, output_field=None, **extra)
  2060. Computes the sum of all values of the given expression.
  2061. * Default alias: ``<field>__sum``
  2062. * Return type: same as input field, or ``output_field`` if supplied
  2063. Variance
  2064. ~~~~~~~~
  2065. .. class:: Variance(expression, sample=False, **extra)
  2066. Returns the variance of the data in the provided expression.
  2067. * Default alias: ``<field>__variance``
  2068. * Return type: ``float``
  2069. Has one optional argument:
  2070. .. attribute:: sample
  2071. By default, ``Variance`` returns the population variance. However,
  2072. if ``sample=True``, the return value will be the sample variance.
  2073. .. admonition:: SQLite
  2074. SQLite doesn't provide ``Variance`` out of the box. An implementation
  2075. is available as an extension module for SQLite. Consult the `SQlite
  2076. documentation`_ for instructions on obtaining and installing this
  2077. extension.
  2078. .. _SQLite documentation: http://www.sqlite.org/contrib
  2079. Query-related classes
  2080. =====================
  2081. This section provides reference material for query-related tools not documented
  2082. elsewhere.
  2083. ``Q()`` objects
  2084. ---------------
  2085. .. class:: Q
  2086. A ``Q()`` object, like an :class:`~django.db.models.F` object, encapsulates a
  2087. SQL expression in a Python object that can be used in database-related
  2088. operations.
  2089. In general, ``Q() objects`` make it possible to define and reuse conditions.
  2090. This permits the :ref:`construction of complex database queries
  2091. <complex-lookups-with-q>` using ``|`` (``OR``) and ``&`` (``AND``) operators;
  2092. in particular, it is not otherwise possible to use ``OR`` in ``QuerySets``.
  2093. ``Prefetch()`` objects
  2094. ----------------------
  2095. .. class:: Prefetch(lookup, queryset=None, to_attr=None)
  2096. The ``Prefetch()`` object can be used to control the operation of
  2097. :meth:`~django.db.models.query.QuerySet.prefetch_related()`.
  2098. The ``lookup`` argument describes the relations to follow and works the same
  2099. as the string based lookups passed to
  2100. :meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example:
  2101. >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all()
  2102. [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
  2103. # This will only execute two queries regardless of the number of Question
  2104. # and Choice objects.
  2105. >>> Question.objects.prefetch_related(Prefetch('choice_set')).all()
  2106. [<Question: Question object>]
  2107. The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup.
  2108. This is useful to further filter down the prefetch operation, or to call
  2109. :meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched
  2110. relation, hence reducing the number of queries even further:
  2111. >>> voted_choices = Choice.objects.filter(votes__gt=0)
  2112. >>> voted_choices
  2113. [<Choice: The sky>]
  2114. >>> prefetch = Prefetch('choice_set', queryset=voted_choices)
  2115. >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()
  2116. [<Choice: The sky>]
  2117. The ``to_attr`` argument sets the result of the prefetch operation to a custom
  2118. attribute:
  2119. >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')
  2120. >>> Question.objects.prefetch_related(prefetch).get().voted_choices
  2121. [<Choice: The sky>]
  2122. >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()
  2123. [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
  2124. .. note::
  2125. When using ``to_attr`` the prefetched result is stored in a list. This can
  2126. provide a significant speed improvement over traditional
  2127. ``prefetch_related`` calls which store the cached result within a
  2128. ``QuerySet`` instance.