querysets.txt 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  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 blog models
  10. <queryset-model-example>` presented in the :doc:`database query guide
  11. </topics/db/queries>`.
  12. .. _when-querysets-are-evaluated:
  13. When ``QuerySet``\s 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. * **Asynchronous iteration.**. A ``QuerySet`` can also be iterated over using
  27. ``async for``::
  28. async for e in Entry.objects.all():
  29. results.append(e)
  30. Both synchronous and asynchronous iterators of QuerySets share the same
  31. underlying cache.
  32. .. versionchanged:: 4.1
  33. Support for asynchronous iteration was added.
  34. * **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
  35. be sliced, using Python's array-slicing syntax. Slicing an unevaluated
  36. ``QuerySet`` usually returns another unevaluated ``QuerySet``, but Django
  37. will execute the database query if you use the "step" parameter of slice
  38. syntax, and will return a list. Slicing a ``QuerySet`` that has been
  39. evaluated also returns a list.
  40. Also note that even though slicing an unevaluated ``QuerySet`` returns
  41. another unevaluated ``QuerySet``, modifying it further (e.g., adding
  42. more filters, or modifying ordering) is not allowed, since that does not
  43. translate well into SQL and it would not have a clear meaning either.
  44. * **Pickling/Caching.** See the following section for details of what
  45. is involved when `pickling QuerySets`_. The important thing for the
  46. purposes of this section is that the results are read from the database.
  47. * **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
  48. This is for convenience in the Python interactive interpreter, so you can
  49. immediately see your results when using the API interactively.
  50. * **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
  51. This, as you might expect, returns the length of the result list.
  52. Note: If you only need to determine the number of records in the set (and
  53. don't need the actual objects), it's much more efficient to handle a count
  54. at the database level using SQL's ``SELECT COUNT(*)``. Django provides a
  55. :meth:`~QuerySet.count` method for precisely this reason.
  56. * **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
  57. it. For example::
  58. entry_list = list(Entry.objects.all())
  59. * **bool().** Testing a ``QuerySet`` in a boolean context, such as using
  60. ``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query
  61. to be executed. If there is at least one result, the ``QuerySet`` is
  62. ``True``, otherwise ``False``. For example::
  63. if Entry.objects.filter(headline="Test"):
  64. print("There is at least one Entry with the headline Test")
  65. Note: If you only want to determine if at least one result exists (and don't
  66. need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`.
  67. .. _pickling QuerySets:
  68. Pickling ``QuerySet``\s
  69. -----------------------
  70. If you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded
  71. into memory prior to pickling. Pickling is usually used as a precursor to
  72. caching and when the cached queryset is reloaded, you want the results to
  73. already be present and ready for use (reading from the database can take some
  74. time, defeating the purpose of caching). This means that when you unpickle a
  75. ``QuerySet``, it contains the results at the moment it was pickled, rather
  76. than the results that are currently in the database.
  77. If you only want to pickle the necessary information to recreate the
  78. ``QuerySet`` from the database at a later time, pickle the ``query`` attribute
  79. of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
  80. any results loaded) using some code like this::
  81. >>> import pickle
  82. >>> query = pickle.loads(s) # Assuming 's' is the pickled string.
  83. >>> qs = MyModel.objects.all()
  84. >>> qs.query = query # Restore the original 'query'.
  85. The ``query`` attribute is an opaque object. It represents the internals of
  86. the query construction and is not part of the public API. However, it is safe
  87. (and fully supported) to pickle and unpickle the attribute's contents as
  88. described here.
  89. .. admonition:: Restrictions on ``QuerySet.values_list()``
  90. If you recreate :meth:`QuerySet.values_list` using the pickled ``query``
  91. attribute, it will be converted to :meth:`QuerySet.values`::
  92. >>> import pickle
  93. >>> qs = Blog.objects.values_list('id', 'name')
  94. >>> qs
  95. <QuerySet [(1, 'Beatles Blog')]>
  96. >>> reloaded_qs = Blog.objects.all()
  97. >>> reloaded_qs.query = pickle.loads(pickle.dumps(qs.query))
  98. >>> reloaded_qs
  99. <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
  100. .. admonition:: You can't share pickles between versions
  101. Pickles of ``QuerySets`` are only valid for the version of Django that
  102. was used to generate them. If you generate a pickle using Django
  103. version N, there is no guarantee that pickle will be readable with
  104. Django version N+1. Pickles should not be used as part of a long-term
  105. archival strategy.
  106. Since pickle compatibility errors can be difficult to diagnose, such as
  107. silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
  108. unpickle a queryset in a Django version that is different than the one in
  109. which it was pickled.
  110. .. _queryset-api:
  111. ``QuerySet`` API
  112. ================
  113. Here's the formal declaration of a ``QuerySet``:
  114. .. class:: QuerySet(model=None, query=None, using=None, hints=None)
  115. Usually when you'll interact with a ``QuerySet`` you'll use it by
  116. :ref:`chaining filters <chaining-filters>`. To make this work, most
  117. ``QuerySet`` methods return new querysets. These methods are covered in
  118. detail later in this section.
  119. The ``QuerySet`` class has the following public attributes you can use for
  120. introspection:
  121. .. attribute:: ordered
  122. ``True`` if the ``QuerySet`` is ordered — i.e. has an
  123. :meth:`order_by()` clause or a default ordering on the model.
  124. ``False`` otherwise.
  125. .. attribute:: db
  126. The database that will be used if this query is executed now.
  127. .. note::
  128. The ``query`` parameter to :class:`QuerySet` exists so that specialized
  129. query subclasses can reconstruct internal query state. The value of the
  130. parameter is an opaque representation of that query state and is not
  131. part of a public API.
  132. .. currentmodule:: django.db.models.query.QuerySet
  133. Methods that return new ``QuerySet``\s
  134. --------------------------------------
  135. Django provides a range of ``QuerySet`` refinement methods that modify either
  136. the types of results returned by the ``QuerySet`` or the way its SQL query is
  137. executed.
  138. .. note::
  139. These methods do not run database queries, therefore they are **safe to**
  140. **run in asynchronous code**, and do not have separate asynchronous
  141. versions.
  142. ``filter()``
  143. ~~~~~~~~~~~~
  144. .. method:: filter(*args, **kwargs)
  145. Returns a new ``QuerySet`` containing objects that match the given lookup
  146. parameters.
  147. The lookup parameters (``**kwargs``) should be in the format described in
  148. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
  149. underlying SQL statement.
  150. If you need to execute more complex queries (for example, queries with ``OR`` statements),
  151. you can use :class:`Q objects <django.db.models.Q>` (``*args``).
  152. ``exclude()``
  153. ~~~~~~~~~~~~~
  154. .. method:: exclude(*args, **kwargs)
  155. Returns a new ``QuerySet`` containing objects that do *not* match the given
  156. lookup parameters.
  157. The lookup parameters (``**kwargs``) should be in the format described in
  158. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
  159. underlying SQL statement, and the whole thing is enclosed in a ``NOT()``.
  160. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
  161. AND whose ``headline`` is "Hello"::
  162. Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
  163. In SQL terms, that evaluates to:
  164. .. code-block:: sql
  165. SELECT ...
  166. WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
  167. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
  168. OR whose headline is "Hello"::
  169. Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
  170. In SQL terms, that evaluates to:
  171. .. code-block:: sql
  172. SELECT ...
  173. WHERE NOT pub_date > '2005-1-3'
  174. AND NOT headline = 'Hello'
  175. Note the second example is more restrictive.
  176. If you need to execute more complex queries (for example, queries with ``OR`` statements),
  177. you can use :class:`Q objects <django.db.models.Q>` (``*args``).
  178. ``annotate()``
  179. ~~~~~~~~~~~~~~
  180. .. method:: annotate(*args, **kwargs)
  181. Annotates each object in the ``QuerySet`` with the provided list of :doc:`query
  182. expressions </ref/models/expressions>`. An expression may be a simple value, a
  183. reference to a field on the model (or any related models), or an aggregate
  184. expression (averages, sums, etc.) that has been computed over the objects that
  185. are related to the objects in the ``QuerySet``.
  186. Each argument to ``annotate()`` is an annotation that will be added
  187. to each object in the ``QuerySet`` that is returned.
  188. The aggregation functions that are provided by Django are described
  189. in `Aggregation Functions`_ below.
  190. Annotations specified using keyword arguments will use the keyword as
  191. the alias for the annotation. Anonymous arguments will have an alias
  192. generated for them based upon the name of the aggregate function and
  193. the model field that is being aggregated. Only aggregate expressions
  194. that reference a single field can be anonymous arguments. Everything
  195. else must be a keyword argument.
  196. For example, if you were manipulating a list of blogs, you may want
  197. to determine how many entries have been made in each blog::
  198. >>> from django.db.models import Count
  199. >>> q = Blog.objects.annotate(Count('entry'))
  200. # The name of the first blog
  201. >>> q[0].name
  202. 'Blogasaurus'
  203. # The number of entries on the first blog
  204. >>> q[0].entry__count
  205. 42
  206. The ``Blog`` model doesn't define an ``entry__count`` attribute by itself,
  207. but by using a keyword argument to specify the aggregate function, you can
  208. control the name of the annotation::
  209. >>> q = Blog.objects.annotate(number_of_entries=Count('entry'))
  210. # The number of entries on the first blog, using the name provided
  211. >>> q[0].number_of_entries
  212. 42
  213. For an in-depth discussion of aggregation, see :doc:`the topic guide on
  214. Aggregation </topics/db/aggregation>`.
  215. ``alias()``
  216. ~~~~~~~~~~~
  217. .. method:: alias(*args, **kwargs)
  218. Same as :meth:`annotate`, but instead of annotating objects in the
  219. ``QuerySet``, saves the expression for later reuse with other ``QuerySet``
  220. methods. This is useful when the result of the expression itself is not needed
  221. but it is used for filtering, ordering, or as a part of a complex expression.
  222. Not selecting the unused value removes redundant work from the database which
  223. should result in better performance.
  224. For example, if you want to find blogs with more than 5 entries, but are not
  225. interested in the exact number of entries, you could do this::
  226. >>> from django.db.models import Count
  227. >>> blogs = Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)
  228. ``alias()`` can be used in conjunction with :meth:`annotate`, :meth:`exclude`,
  229. :meth:`filter`, :meth:`order_by`, and :meth:`update`. To use aliased expression
  230. with other methods (e.g. :meth:`aggregate`), you must promote it to an
  231. annotation::
  232. Blog.objects.alias(entries=Count('entry')).annotate(
  233. entries=F('entries'),
  234. ).aggregate(Sum('entries'))
  235. :meth:`filter` and :meth:`order_by` can take expressions directly, but
  236. expression construction and usage often does not happen in the same place (for
  237. example, ``QuerySet`` method creates expressions, for later use in views).
  238. ``alias()`` allows building complex expressions incrementally, possibly
  239. spanning multiple methods and modules, refer to the expression parts by their
  240. aliases and only use :meth:`annotate` for the final result.
  241. ``order_by()``
  242. ~~~~~~~~~~~~~~
  243. .. method:: order_by(*fields)
  244. By default, results returned by a ``QuerySet`` are ordered by the ordering
  245. tuple given by the ``ordering`` option in the model's ``Meta``. You can
  246. override this on a per-``QuerySet`` basis by using the ``order_by`` method.
  247. Example::
  248. Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
  249. The result above will be ordered by ``pub_date`` descending, then by
  250. ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
  251. *descending* order. Ascending order is implied. To order randomly, use ``"?"``,
  252. like so::
  253. Entry.objects.order_by('?')
  254. Note: ``order_by('?')`` queries may be expensive and slow, depending on the
  255. database backend you're using.
  256. To order by a field in a different model, use the same syntax as when you are
  257. querying across model relations. That is, the name of the field, followed by a
  258. double underscore (``__``), followed by the name of the field in the new model,
  259. and so on for as many models as you want to join. For example::
  260. Entry.objects.order_by('blog__name', 'headline')
  261. If you try to order by a field that is a relation to another model, Django will
  262. use the default ordering on the related model, or order by the related model's
  263. primary key if there is no :attr:`Meta.ordering
  264. <django.db.models.Options.ordering>` specified. For example, since the ``Blog``
  265. model has no default ordering specified::
  266. Entry.objects.order_by('blog')
  267. ...is identical to::
  268. Entry.objects.order_by('blog__id')
  269. If ``Blog`` had ``ordering = ['name']``, then the first queryset would be
  270. identical to::
  271. Entry.objects.order_by('blog__name')
  272. You can also order by :doc:`query expressions </ref/models/expressions>` by
  273. calling :meth:`~.Expression.asc` or :meth:`~.Expression.desc` on the
  274. expression::
  275. Entry.objects.order_by(Coalesce('summary', 'headline').desc())
  276. :meth:`~.Expression.asc` and :meth:`~.Expression.desc` have arguments
  277. (``nulls_first`` and ``nulls_last``) that control how null values are sorted.
  278. Be cautious when ordering by fields in related models if you are also using
  279. :meth:`distinct()`. See the note in :meth:`distinct` for an explanation of how
  280. related model ordering can change the expected results.
  281. .. note::
  282. It is permissible to specify a multi-valued field to order the results by
  283. (for example, a :class:`~django.db.models.ManyToManyField` field, or the
  284. reverse relation of a :class:`~django.db.models.ForeignKey` field).
  285. Consider this case::
  286. class Event(Model):
  287. parent = models.ForeignKey(
  288. 'self',
  289. on_delete=models.CASCADE,
  290. related_name='children',
  291. )
  292. date = models.DateField()
  293. Event.objects.order_by('children__date')
  294. Here, there could potentially be multiple ordering data for each ``Event``;
  295. each ``Event`` with multiple ``children`` will be returned multiple times
  296. into the new ``QuerySet`` that ``order_by()`` creates. In other words,
  297. using ``order_by()`` on the ``QuerySet`` could return more items than you
  298. were working on to begin with - which is probably neither expected nor
  299. useful.
  300. Thus, take care when using multi-valued field to order the results. **If**
  301. you can be sure that there will only be one ordering piece of data for each
  302. of the items you're ordering, this approach should not present problems. If
  303. not, make sure the results are what you expect.
  304. There's no way to specify whether ordering should be case sensitive. With
  305. respect to case-sensitivity, Django will order results however your database
  306. backend normally orders them.
  307. You can order by a field converted to lowercase with
  308. :class:`~django.db.models.functions.Lower` which will achieve case-consistent
  309. ordering::
  310. Entry.objects.order_by(Lower('headline').desc())
  311. If you don't want any ordering to be applied to a query, not even the default
  312. ordering, call :meth:`order_by()` with no parameters.
  313. You can tell if a query is ordered or not by checking the
  314. :attr:`.QuerySet.ordered` attribute, which will be ``True`` if the
  315. ``QuerySet`` has been ordered in any way.
  316. Each ``order_by()`` call will clear any previous ordering. For example, this
  317. query will be ordered by ``pub_date`` and not ``headline``::
  318. Entry.objects.order_by('headline').order_by('pub_date')
  319. .. warning::
  320. Ordering is not a free operation. Each field you add to the ordering
  321. incurs a cost to your database. Each foreign key you add will
  322. implicitly include all of its default orderings as well.
  323. If a query doesn't have an ordering specified, results are returned from
  324. the database in an unspecified order. A particular ordering is guaranteed
  325. only when ordering by a set of fields that uniquely identify each object in
  326. the results. For example, if a ``name`` field isn't unique, ordering by it
  327. won't guarantee objects with the same name always appear in the same order.
  328. ``reverse()``
  329. ~~~~~~~~~~~~~
  330. .. method:: reverse()
  331. Use the ``reverse()`` method to reverse the order in which a queryset's
  332. elements are returned. Calling ``reverse()`` a second time restores the
  333. ordering back to the normal direction.
  334. To retrieve the "last" five items in a queryset, you could do this::
  335. my_queryset.reverse()[:5]
  336. Note that this is not quite the same as slicing from the end of a sequence in
  337. Python. The above example will return the last item first, then the
  338. penultimate item and so on. If we had a Python sequence and looked at
  339. ``seq[-5:]``, we would see the fifth-last item first. Django doesn't support
  340. that mode of access (slicing from the end), because it's not possible to do it
  341. efficiently in SQL.
  342. Also, note that ``reverse()`` should generally only be called on a ``QuerySet``
  343. which has a defined ordering (e.g., when querying against a model which defines
  344. a default ordering, or when using :meth:`order_by()`). If no such ordering is
  345. defined for a given ``QuerySet``, calling ``reverse()`` on it has no real
  346. effect (the ordering was undefined prior to calling ``reverse()``, and will
  347. remain undefined afterward).
  348. ``distinct()``
  349. ~~~~~~~~~~~~~~
  350. .. method:: distinct(*fields)
  351. Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
  352. eliminates duplicate rows from the query results.
  353. By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
  354. is rarely a problem, because simple queries such as ``Blog.objects.all()``
  355. don't introduce the possibility of duplicate result rows. However, if your
  356. query spans multiple tables, it's possible to get duplicate results when a
  357. ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
  358. .. note::
  359. Any fields used in an :meth:`order_by` call are included in the SQL
  360. ``SELECT`` columns. This can sometimes lead to unexpected results when used
  361. in conjunction with ``distinct()``. If you order by fields from a related
  362. model, those fields will be added to the selected columns and they may make
  363. otherwise duplicate rows appear to be distinct. Since the extra columns
  364. don't appear in the returned results (they are only there to support
  365. ordering), it sometimes looks like non-distinct results are being returned.
  366. Similarly, if you use a :meth:`values()` query to restrict the columns
  367. selected, the columns used in any :meth:`order_by()` (or default model
  368. ordering) will still be involved and may affect uniqueness of the results.
  369. The moral here is that if you are using ``distinct()`` be careful about
  370. ordering by related models. Similarly, when using ``distinct()`` and
  371. :meth:`values()` together, be careful when ordering by fields not in the
  372. :meth:`values()` call.
  373. On PostgreSQL only, you can pass positional arguments (``*fields``) in order to
  374. specify the names of fields to which the ``DISTINCT`` should apply. This
  375. translates to a ``SELECT DISTINCT ON`` SQL query. Here's the difference. For a
  376. normal ``distinct()`` call, the database compares *each* field in each row when
  377. determining which rows are distinct. For a ``distinct()`` call with specified
  378. field names, the database will only compare the specified field names.
  379. .. note::
  380. When you specify field names, you *must* provide an ``order_by()`` in the
  381. ``QuerySet``, and the fields in ``order_by()`` must start with the fields in
  382. ``distinct()``, in the same order.
  383. For example, ``SELECT DISTINCT ON (a)`` gives you the first row for each
  384. value in column ``a``. If you don't specify an order, you'll get some
  385. arbitrary row.
  386. Examples (those after the first will only work on PostgreSQL)::
  387. >>> Author.objects.distinct()
  388. [...]
  389. >>> Entry.objects.order_by('pub_date').distinct('pub_date')
  390. [...]
  391. >>> Entry.objects.order_by('blog').distinct('blog')
  392. [...]
  393. >>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
  394. [...]
  395. >>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
  396. [...]
  397. >>> Entry.objects.order_by('author', 'pub_date').distinct('author')
  398. [...]
  399. .. note::
  400. Keep in mind that :meth:`order_by` uses any default related model ordering
  401. that has been defined. You might have to explicitly order by the relation
  402. ``_id`` or referenced field to make sure the ``DISTINCT ON`` expressions
  403. match those at the beginning of the ``ORDER BY`` clause. For example, if
  404. the ``Blog`` model defined an :attr:`~django.db.models.Options.ordering` by
  405. ``name``::
  406. Entry.objects.order_by('blog').distinct('blog')
  407. ...wouldn't work because the query would be ordered by ``blog__name`` thus
  408. mismatching the ``DISTINCT ON`` expression. You'd have to explicitly order
  409. by the relation ``_id`` field (``blog_id`` in this case) or the referenced
  410. one (``blog__pk``) to make sure both expressions match.
  411. ``values()``
  412. ~~~~~~~~~~~~
  413. .. method:: values(*fields, **expressions)
  414. Returns a ``QuerySet`` that returns dictionaries, rather than model instances,
  415. when used as an iterable.
  416. Each of those dictionaries represents an object, with the keys corresponding to
  417. the attribute names of model objects.
  418. This example compares the dictionaries of ``values()`` with the normal model
  419. objects::
  420. # This list contains a Blog object.
  421. >>> Blog.objects.filter(name__startswith='Beatles')
  422. <QuerySet [<Blog: Beatles Blog>]>
  423. # This list contains a dictionary.
  424. >>> Blog.objects.filter(name__startswith='Beatles').values()
  425. <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
  426. The ``values()`` method takes optional positional arguments, ``*fields``, which
  427. specify field names to which the ``SELECT`` should be limited. If you specify
  428. the fields, each dictionary will contain only the field keys/values for the
  429. fields you specify. If you don't specify the fields, each dictionary will
  430. contain a key and value for every field in the database table.
  431. Example::
  432. >>> Blog.objects.values()
  433. <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
  434. >>> Blog.objects.values('id', 'name')
  435. <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
  436. The ``values()`` method also takes optional keyword arguments,
  437. ``**expressions``, which are passed through to :meth:`annotate`::
  438. >>> from django.db.models.functions import Lower
  439. >>> Blog.objects.values(lower_name=Lower('name'))
  440. <QuerySet [{'lower_name': 'beatles blog'}]>
  441. You can use built-in and :doc:`custom lookups </howto/custom-lookups>` in
  442. ordering. For example::
  443. >>> from django.db.models import CharField
  444. >>> from django.db.models.functions import Lower
  445. >>> CharField.register_lookup(Lower)
  446. >>> Blog.objects.values('name__lower')
  447. <QuerySet [{'name__lower': 'beatles blog'}]>
  448. An aggregate within a ``values()`` clause is applied before other arguments
  449. within the same ``values()`` clause. If you need to group by another value,
  450. add it to an earlier ``values()`` clause instead. For example::
  451. >>> from django.db.models import Count
  452. >>> Blog.objects.values('entry__authors', entries=Count('entry'))
  453. <QuerySet [{'entry__authors': 1, 'entries': 20}, {'entry__authors': 1, 'entries': 13}]>
  454. >>> Blog.objects.values('entry__authors').annotate(entries=Count('entry'))
  455. <QuerySet [{'entry__authors': 1, 'entries': 33}]>
  456. A few subtleties that are worth mentioning:
  457. * If you have a field called ``foo`` that is a
  458. :class:`~django.db.models.ForeignKey`, the default ``values()`` call
  459. will return a dictionary key called ``foo_id``, since this is the name
  460. of the hidden model attribute that stores the actual value (the ``foo``
  461. attribute refers to the related model). When you are calling
  462. ``values()`` and passing in field names, you can pass in either ``foo``
  463. or ``foo_id`` and you will get back the same thing (the dictionary key
  464. will match the field name you passed in).
  465. For example::
  466. >>> Entry.objects.values()
  467. <QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>
  468. >>> Entry.objects.values('blog')
  469. <QuerySet [{'blog': 1}, ...]>
  470. >>> Entry.objects.values('blog_id')
  471. <QuerySet [{'blog_id': 1}, ...]>
  472. * When using ``values()`` together with :meth:`distinct()`, be aware that
  473. ordering can affect the results. See the note in :meth:`distinct` for
  474. details.
  475. * If you use a ``values()`` clause after an :meth:`extra()` call,
  476. any fields defined by a ``select`` argument in the :meth:`extra()` must
  477. be explicitly included in the ``values()`` call. Any :meth:`extra()` call
  478. made after a ``values()`` call will have its extra selected fields
  479. ignored.
  480. * Calling :meth:`only()` and :meth:`defer()` after ``values()`` doesn't make
  481. sense, so doing so will raise a ``TypeError``.
  482. * Combining transforms and aggregates requires the use of two :meth:`annotate`
  483. calls, either explicitly or as keyword arguments to :meth:`values`. As above,
  484. if the transform has been registered on the relevant field type the first
  485. :meth:`annotate` can be omitted, thus the following examples are equivalent::
  486. >>> from django.db.models import CharField, Count
  487. >>> from django.db.models.functions import Lower
  488. >>> CharField.register_lookup(Lower)
  489. >>> Blog.objects.values('entry__authors__name__lower').annotate(entries=Count('entry'))
  490. <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
  491. >>> Blog.objects.values(
  492. ... entry__authors__name__lower=Lower('entry__authors__name')
  493. ... ).annotate(entries=Count('entry'))
  494. <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
  495. >>> Blog.objects.annotate(
  496. ... entry__authors__name__lower=Lower('entry__authors__name')
  497. ... ).values('entry__authors__name__lower').annotate(entries=Count('entry'))
  498. <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
  499. It is useful when you know you're only going to need values from a small number
  500. of the available fields and you won't need the functionality of a model
  501. instance object. It's more efficient to select only the fields you need to use.
  502. Finally, note that you can call ``filter()``, ``order_by()``, etc. after the
  503. ``values()`` call, that means that these two calls are identical::
  504. Blog.objects.values().order_by('id')
  505. Blog.objects.order_by('id').values()
  506. The people who made Django prefer to put all the SQL-affecting methods first,
  507. followed (optionally) by any output-affecting methods (such as ``values()``),
  508. but it doesn't really matter. This is your chance to really flaunt your
  509. individualism.
  510. You can also refer to fields on related models with reverse relations through
  511. ``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes::
  512. >>> Blog.objects.values('name', 'entry__headline')
  513. <QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'},
  514. {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]>
  515. .. warning::
  516. Because :class:`~django.db.models.ManyToManyField` attributes and reverse
  517. relations can have multiple related rows, including these can have a
  518. multiplier effect on the size of your result set. This will be especially
  519. pronounced if you include multiple such fields in your ``values()`` query,
  520. in which case all possible combinations will be returned.
  521. .. admonition:: Special values for ``JSONField`` on SQLite
  522. Due to the way the ``JSON_EXTRACT`` and ``JSON_TYPE`` SQL functions are
  523. implemented on SQLite, and lack of the ``BOOLEAN`` data type,
  524. ``values()`` will return ``True``, ``False``, and ``None`` instead of
  525. ``"true"``, ``"false"``, and ``"null"`` strings for
  526. :class:`~django.db.models.JSONField` key transforms.
  527. ``values_list()``
  528. ~~~~~~~~~~~~~~~~~
  529. .. method:: values_list(*fields, flat=False, named=False)
  530. This is similar to ``values()`` except that instead of returning dictionaries,
  531. it returns tuples when iterated over. Each tuple contains the value from the
  532. respective field or expression passed into the ``values_list()`` call — so the
  533. first item is the first field, etc. For example::
  534. >>> Entry.objects.values_list('id', 'headline')
  535. <QuerySet [(1, 'First entry'), ...]>
  536. >>> from django.db.models.functions import Lower
  537. >>> Entry.objects.values_list('id', Lower('headline'))
  538. <QuerySet [(1, 'first entry'), ...]>
  539. If you only pass in a single field, you can also pass in the ``flat``
  540. parameter. If ``True``, this will mean the returned results are single values,
  541. rather than one-tuples. An example should make the difference clearer::
  542. >>> Entry.objects.values_list('id').order_by('id')
  543. <QuerySet[(1,), (2,), (3,), ...]>
  544. >>> Entry.objects.values_list('id', flat=True).order_by('id')
  545. <QuerySet [1, 2, 3, ...]>
  546. It is an error to pass in ``flat`` when there is more than one field.
  547. You can pass ``named=True`` to get results as a
  548. :func:`~python:collections.namedtuple`::
  549. >>> Entry.objects.values_list('id', 'headline', named=True)
  550. <QuerySet [Row(id=1, headline='First entry'), ...]>
  551. Using a named tuple may make use of the results more readable, at the expense
  552. of a small performance penalty for transforming the results into a named tuple.
  553. If you don't pass any values to ``values_list()``, it will return all the
  554. fields in the model, in the order they were declared.
  555. A common need is to get a specific field value of a certain model instance. To
  556. achieve that, use ``values_list()`` followed by a ``get()`` call::
  557. >>> Entry.objects.values_list('headline', flat=True).get(pk=1)
  558. 'First entry'
  559. ``values()`` and ``values_list()`` are both intended as optimizations for a
  560. specific use case: retrieving a subset of data without the overhead of creating
  561. a model instance. This metaphor falls apart when dealing with many-to-many and
  562. other multivalued relations (such as the one-to-many relation of a reverse
  563. foreign key) because the "one row, one object" assumption doesn't hold.
  564. For example, notice the behavior when querying across a
  565. :class:`~django.db.models.ManyToManyField`::
  566. >>> Author.objects.values_list('name', 'entry__headline')
  567. <QuerySet [('Noam Chomsky', 'Impressions of Gaza'),
  568. ('George Orwell', 'Why Socialists Do Not Believe in Fun'),
  569. ('George Orwell', 'In Defence of English Cooking'),
  570. ('Don Quixote', None)]>
  571. Authors with multiple entries appear multiple times and authors without any
  572. entries have ``None`` for the entry headline.
  573. Similarly, when querying a reverse foreign key, ``None`` appears for entries
  574. not having any author::
  575. >>> Entry.objects.values_list('authors')
  576. <QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>
  577. .. admonition:: Special values for ``JSONField`` on SQLite
  578. Due to the way the ``JSON_EXTRACT`` and ``JSON_TYPE`` SQL functions are
  579. implemented on SQLite, and lack of the ``BOOLEAN`` data type,
  580. ``values_list()`` will return ``True``, ``False``, and ``None`` instead of
  581. ``"true"``, ``"false"``, and ``"null"`` strings for
  582. :class:`~django.db.models.JSONField` key transforms.
  583. ``dates()``
  584. ~~~~~~~~~~~
  585. .. method:: dates(field, kind, order='ASC')
  586. Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.date`
  587. objects representing all available dates of a particular kind within the
  588. contents of the ``QuerySet``.
  589. ``field`` should be the name of a ``DateField`` of your model.
  590. ``kind`` should be either ``"year"``, ``"month"``, ``"week"``, or ``"day"``.
  591. Each :class:`datetime.date` object in the result list is "truncated" to the
  592. given ``type``.
  593. * ``"year"`` returns a list of all distinct year values for the field.
  594. * ``"month"`` returns a list of all distinct year/month values for the
  595. field.
  596. * ``"week"`` returns a list of all distinct year/week values for the field. All
  597. dates will be a Monday.
  598. * ``"day"`` returns a list of all distinct year/month/day values for the
  599. field.
  600. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
  601. ``'DESC'``. This specifies how to order the results.
  602. Examples::
  603. >>> Entry.objects.dates('pub_date', 'year')
  604. [datetime.date(2005, 1, 1)]
  605. >>> Entry.objects.dates('pub_date', 'month')
  606. [datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
  607. >>> Entry.objects.dates('pub_date', 'week')
  608. [datetime.date(2005, 2, 14), datetime.date(2005, 3, 14)]
  609. >>> Entry.objects.dates('pub_date', 'day')
  610. [datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]
  611. >>> Entry.objects.dates('pub_date', 'day', order='DESC')
  612. [datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]
  613. >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
  614. [datetime.date(2005, 3, 20)]
  615. ``datetimes()``
  616. ~~~~~~~~~~~~~~~
  617. .. method:: datetimes(field_name, kind, order='ASC', tzinfo=None, is_dst=None)
  618. Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.datetime`
  619. objects representing all available dates of a particular kind within the
  620. contents of the ``QuerySet``.
  621. ``field_name`` should be the name of a ``DateTimeField`` of your model.
  622. ``kind`` should be either ``"year"``, ``"month"``, ``"week"``, ``"day"``,
  623. ``"hour"``, ``"minute"``, or ``"second"``. Each :class:`datetime.datetime`
  624. object in the result list is "truncated" to the given ``type``.
  625. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
  626. ``'DESC'``. This specifies how to order the results.
  627. ``tzinfo`` defines the time zone to which datetimes are converted prior to
  628. truncation. Indeed, a given datetime has different representations depending
  629. on the time zone in use. This parameter must be a :class:`datetime.tzinfo`
  630. object. If it's ``None``, Django uses the :ref:`current time zone
  631. <default-current-time-zone>`. It has no effect when :setting:`USE_TZ` is
  632. ``False``.
  633. ``is_dst`` indicates whether or not ``pytz`` should interpret nonexistent and
  634. ambiguous datetimes in daylight saving time. By default (when ``is_dst=None``),
  635. ``pytz`` raises an exception for such datetimes.
  636. .. deprecated:: 4.0
  637. The ``is_dst`` parameter is deprecated and will be removed in Django 5.0.
  638. .. _database-time-zone-definitions:
  639. .. note::
  640. This function performs time zone conversions directly in the database.
  641. As a consequence, your database must be able to interpret the value of
  642. ``tzinfo.tzname(None)``. This translates into the following requirements:
  643. - SQLite: no requirements. Conversions are performed in Python.
  644. - PostgreSQL: no requirements (see `Time Zones`_).
  645. - Oracle: no requirements (see `Choosing a Time Zone File`_).
  646. - MySQL: load the time zone tables with `mysql_tzinfo_to_sql`_.
  647. .. _Time Zones: https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES
  648. .. _Choosing a Time Zone File: https://docs.oracle.com/en/database/oracle/
  649. oracle-database/18/nlspg/datetime-data-types-and-time-zone-support.html
  650. #GUID-805AB986-DE12-4FEA-AF56-5AABCD2132DF
  651. .. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
  652. ``none()``
  653. ~~~~~~~~~~
  654. .. method:: none()
  655. Calling ``none()`` will create a queryset that never returns any objects and no
  656. query will be executed when accessing the results. A ``qs.none()`` queryset
  657. is an instance of ``EmptyQuerySet``.
  658. Examples::
  659. >>> Entry.objects.none()
  660. <QuerySet []>
  661. >>> from django.db.models.query import EmptyQuerySet
  662. >>> isinstance(Entry.objects.none(), EmptyQuerySet)
  663. True
  664. ``all()``
  665. ~~~~~~~~~
  666. .. method:: all()
  667. Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass). This
  668. can be useful in situations where you might want to pass in either a model
  669. manager or a ``QuerySet`` and do further filtering on the result. After calling
  670. ``all()`` on either object, you'll definitely have a ``QuerySet`` to work with.
  671. When a ``QuerySet`` is :ref:`evaluated <when-querysets-are-evaluated>`, it
  672. typically caches its results. If the data in the database might have changed
  673. since a ``QuerySet`` was evaluated, you can get updated results for the same
  674. query by calling ``all()`` on a previously evaluated ``QuerySet``.
  675. ``union()``
  676. ~~~~~~~~~~~
  677. .. method:: union(*other_qs, all=False)
  678. Uses SQL's ``UNION`` operator to combine the results of two or more
  679. ``QuerySet``\s. For example:
  680. >>> qs1.union(qs2, qs3)
  681. The ``UNION`` operator selects only distinct values by default. To allow
  682. duplicate values, use the ``all=True`` argument.
  683. ``union()``, ``intersection()``, and ``difference()`` return model instances
  684. of the type of the first ``QuerySet`` even if the arguments are ``QuerySet``\s
  685. of other models. Passing different models works as long as the ``SELECT`` list
  686. is the same in all ``QuerySet``\s (at least the types, the names don't matter
  687. as long as the types are in the same order). In such cases, you must use the
  688. column names from the first ``QuerySet`` in ``QuerySet`` methods applied to the
  689. resulting ``QuerySet``. For example::
  690. >>> qs1 = Author.objects.values_list('name')
  691. >>> qs2 = Entry.objects.values_list('headline')
  692. >>> qs1.union(qs2).order_by('name')
  693. In addition, only ``LIMIT``, ``OFFSET``, ``COUNT(*)``, ``ORDER BY``, and
  694. specifying columns (i.e. slicing, :meth:`count`, :meth:`exists`,
  695. :meth:`order_by`, and :meth:`values()`/:meth:`values_list()`) are allowed
  696. on the resulting ``QuerySet``. Further, databases place restrictions on
  697. what operations are allowed in the combined queries. For example, most
  698. databases don't allow ``LIMIT`` or ``OFFSET`` in the combined queries.
  699. ``intersection()``
  700. ~~~~~~~~~~~~~~~~~~
  701. .. method:: intersection(*other_qs)
  702. Uses SQL's ``INTERSECT`` operator to return the shared elements of two or more
  703. ``QuerySet``\s. For example:
  704. >>> qs1.intersection(qs2, qs3)
  705. See :meth:`union` for some restrictions.
  706. ``difference()``
  707. ~~~~~~~~~~~~~~~~
  708. .. method:: difference(*other_qs)
  709. Uses SQL's ``EXCEPT`` operator to keep only elements present in the
  710. ``QuerySet`` but not in some other ``QuerySet``\s. For example::
  711. >>> qs1.difference(qs2, qs3)
  712. See :meth:`union` for some restrictions.
  713. ``select_related()``
  714. ~~~~~~~~~~~~~~~~~~~~
  715. .. method:: select_related(*fields)
  716. Returns a ``QuerySet`` that will "follow" foreign-key relationships, selecting
  717. additional related-object data when it executes its query. This is a
  718. performance booster which results in a single more complex query but means
  719. later use of foreign-key relationships won't require database queries.
  720. The following examples illustrate the difference between plain lookups and
  721. ``select_related()`` lookups. Here's standard lookup::
  722. # Hits the database.
  723. e = Entry.objects.get(id=5)
  724. # Hits the database again to get the related Blog object.
  725. b = e.blog
  726. And here's ``select_related`` lookup::
  727. # Hits the database.
  728. e = Entry.objects.select_related('blog').get(id=5)
  729. # Doesn't hit the database, because e.blog has been prepopulated
  730. # in the previous query.
  731. b = e.blog
  732. You can use ``select_related()`` with any queryset of objects::
  733. from django.utils import timezone
  734. # Find all the blogs with entries scheduled to be published in the future.
  735. blogs = set()
  736. for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):
  737. # Without select_related(), this would make a database query for each
  738. # loop iteration in order to fetch the related blog for each entry.
  739. blogs.add(e.blog)
  740. The order of ``filter()`` and ``select_related()`` chaining isn't important.
  741. These querysets are equivalent::
  742. Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')
  743. Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now())
  744. You can follow foreign keys in a similar way to querying them. If you have the
  745. following models::
  746. from django.db import models
  747. class City(models.Model):
  748. # ...
  749. pass
  750. class Person(models.Model):
  751. # ...
  752. hometown = models.ForeignKey(
  753. City,
  754. on_delete=models.SET_NULL,
  755. blank=True,
  756. null=True,
  757. )
  758. class Book(models.Model):
  759. # ...
  760. author = models.ForeignKey(Person, on_delete=models.CASCADE)
  761. ... then a call to ``Book.objects.select_related('author__hometown').get(id=4)``
  762. will cache the related ``Person`` *and* the related ``City``::
  763. # Hits the database with joins to the author and hometown tables.
  764. b = Book.objects.select_related('author__hometown').get(id=4)
  765. p = b.author # Doesn't hit the database.
  766. c = p.hometown # Doesn't hit the database.
  767. # Without select_related()...
  768. b = Book.objects.get(id=4) # Hits the database.
  769. p = b.author # Hits the database.
  770. c = p.hometown # Hits the database.
  771. You can refer to any :class:`~django.db.models.ForeignKey` or
  772. :class:`~django.db.models.OneToOneField` relation in the list of fields
  773. passed to ``select_related()``.
  774. You can also refer to the reverse direction of a
  775. :class:`~django.db.models.OneToOneField` in the list of fields passed to
  776. ``select_related`` — that is, you can traverse a
  777. :class:`~django.db.models.OneToOneField` back to the object on which the field
  778. is defined. Instead of specifying the field name, use the :attr:`related_name
  779. <django.db.models.ForeignKey.related_name>` for the field on the related object.
  780. There may be some situations where you wish to call ``select_related()`` with a
  781. lot of related objects, or where you don't know all of the relations. In these
  782. cases it is possible to call ``select_related()`` with no arguments. This will
  783. follow all non-null foreign keys it can find - nullable foreign keys must be
  784. specified. This is not recommended in most cases as it is likely to make the
  785. underlying query more complex, and return more data, than is actually needed.
  786. If you need to clear the list of related fields added by past calls of
  787. ``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
  788. >>> without_relations = queryset.select_related(None)
  789. Chaining ``select_related`` calls works in a similar way to other methods -
  790. that is that ``select_related('foo', 'bar')`` is equivalent to
  791. ``select_related('foo').select_related('bar')``.
  792. ``prefetch_related()``
  793. ~~~~~~~~~~~~~~~~~~~~~~
  794. .. method:: prefetch_related(*lookups)
  795. Returns a ``QuerySet`` that will automatically retrieve, in a single batch,
  796. related objects for each of the specified lookups.
  797. This has a similar purpose to ``select_related``, in that both are designed to
  798. stop the deluge of database queries that is caused by accessing related objects,
  799. but the strategy is quite different.
  800. ``select_related`` works by creating an SQL join and including the fields of the
  801. related object in the ``SELECT`` statement. For this reason, ``select_related``
  802. gets the related objects in the same database query. However, to avoid the much
  803. larger result set that would result from joining across a 'many' relationship,
  804. ``select_related`` is limited to single-valued relationships - foreign key and
  805. one-to-one.
  806. ``prefetch_related``, on the other hand, does a separate lookup for each
  807. relationship, and does the 'joining' in Python. This allows it to prefetch
  808. many-to-many and many-to-one objects, which cannot be done using
  809. ``select_related``, in addition to the foreign key and one-to-one relationships
  810. that are supported by ``select_related``. It also supports prefetching of
  811. :class:`~django.contrib.contenttypes.fields.GenericRelation` and
  812. :class:`~django.contrib.contenttypes.fields.GenericForeignKey`, however, it
  813. must be restricted to a homogeneous set of results. For example, prefetching
  814. objects referenced by a ``GenericForeignKey`` is only supported if the query
  815. is restricted to one ``ContentType``.
  816. For example, suppose you have these models::
  817. from django.db import models
  818. class Topping(models.Model):
  819. name = models.CharField(max_length=30)
  820. class Pizza(models.Model):
  821. name = models.CharField(max_length=50)
  822. toppings = models.ManyToManyField(Topping)
  823. def __str__(self):
  824. return "%s (%s)" % (
  825. self.name,
  826. ", ".join(topping.name for topping in self.toppings.all()),
  827. )
  828. and run::
  829. >>> Pizza.objects.all()
  830. ["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...
  831. The problem with this is that every time ``Pizza.__str__()`` asks for
  832. ``self.toppings.all()`` it has to query the database, so
  833. ``Pizza.objects.all()`` will run a query on the Toppings table for **every**
  834. item in the Pizza ``QuerySet``.
  835. We can reduce to just two queries using ``prefetch_related``:
  836. >>> Pizza.objects.prefetch_related('toppings')
  837. This implies a ``self.toppings.all()`` for each ``Pizza``; now each time
  838. ``self.toppings.all()`` is called, instead of having to go to the database for
  839. the items, it will find them in a prefetched ``QuerySet`` cache that was
  840. populated in a single query.
  841. That is, all the relevant toppings will have been fetched in a single query,
  842. and used to make ``QuerySets`` that have a pre-filled cache of the relevant
  843. results; these ``QuerySets`` are then used in the ``self.toppings.all()`` calls.
  844. The additional queries in ``prefetch_related()`` are executed after the
  845. ``QuerySet`` has begun to be evaluated and the primary query has been executed.
  846. If you have an iterable of model instances, you can prefetch related attributes
  847. on those instances using the :func:`~django.db.models.prefetch_related_objects`
  848. function.
  849. Note that the result cache of the primary ``QuerySet`` and all specified related
  850. objects will then be fully loaded into memory. This changes the typical
  851. behavior of ``QuerySets``, which normally try to avoid loading all objects into
  852. memory before they are needed, even after a query has been executed in the
  853. database.
  854. .. note::
  855. Remember that, as always with ``QuerySets``, any subsequent chained methods
  856. which imply a different database query will ignore previously cached
  857. results, and retrieve data using a fresh database query. So, if you write
  858. the following:
  859. >>> pizzas = Pizza.objects.prefetch_related('toppings')
  860. >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas]
  861. ...then the fact that ``pizza.toppings.all()`` has been prefetched will not
  862. help you. The ``prefetch_related('toppings')`` implied
  863. ``pizza.toppings.all()``, but ``pizza.toppings.filter()`` is a new and
  864. different query. The prefetched cache can't help here; in fact it hurts
  865. performance, since you have done a database query that you haven't used. So
  866. use this feature with caution!
  867. Also, if you call the database-altering methods
  868. :meth:`~django.db.models.fields.related.RelatedManager.add`,
  869. :meth:`~django.db.models.fields.related.RelatedManager.remove`,
  870. :meth:`~django.db.models.fields.related.RelatedManager.clear` or
  871. :meth:`~django.db.models.fields.related.RelatedManager.set`, on
  872. :class:`related managers<django.db.models.fields.related.RelatedManager>`,
  873. any prefetched cache for the relation will be cleared.
  874. You can also use the normal join syntax to do related fields of related
  875. fields. Suppose we have an additional model to the example above::
  876. class Restaurant(models.Model):
  877. pizzas = models.ManyToManyField(Pizza, related_name='restaurants')
  878. best_pizza = models.ForeignKey(Pizza, related_name='championed_by', on_delete=models.CASCADE)
  879. The following are all legal:
  880. >>> Restaurant.objects.prefetch_related('pizzas__toppings')
  881. This will prefetch all pizzas belonging to restaurants, and all toppings
  882. belonging to those pizzas. This will result in a total of 3 database queries -
  883. one for the restaurants, one for the pizzas, and one for the toppings.
  884. >>> Restaurant.objects.prefetch_related('best_pizza__toppings')
  885. This will fetch the best pizza and all the toppings for the best pizza for each
  886. restaurant. This will be done in 3 database queries - one for the restaurants,
  887. one for the 'best pizzas', and one for the toppings.
  888. The ``best_pizza`` relationship could also be fetched using ``select_related``
  889. to reduce the query count to 2::
  890. >>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')
  891. Since the prefetch is executed after the main query (which includes the joins
  892. needed by ``select_related``), it is able to detect that the ``best_pizza``
  893. objects have already been fetched, and it will skip fetching them again.
  894. Chaining ``prefetch_related`` calls will accumulate the lookups that are
  895. prefetched. To clear any ``prefetch_related`` behavior, pass ``None`` as a
  896. parameter:
  897. >>> non_prefetched = qs.prefetch_related(None)
  898. One difference to note when using ``prefetch_related`` is that objects created
  899. by a query can be shared between the different objects that they are related to
  900. i.e. a single Python model instance can appear at more than one point in the
  901. tree of objects that are returned. This will normally happen with foreign key
  902. relationships. Typically this behavior will not be a problem, and will in fact
  903. save both memory and CPU time.
  904. While ``prefetch_related`` supports prefetching ``GenericForeignKey``
  905. relationships, the number of queries will depend on the data. Since a
  906. ``GenericForeignKey`` can reference data in multiple tables, one query per table
  907. referenced is needed, rather than one query for all the items. There could be
  908. additional queries on the ``ContentType`` table if the relevant rows have not
  909. already been fetched.
  910. ``prefetch_related`` in most cases will be implemented using an SQL query that
  911. uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause
  912. could be generated, which, depending on the database, might have performance
  913. problems of its own when it comes to parsing or executing the SQL query. Always
  914. profile for your use case!
  915. .. versionchanged:: 4.1
  916. If you use ``iterator()`` to run the query, ``prefetch_related()``
  917. calls will only be observed if a value for ``chunk_size`` is provided.
  918. You can use the :class:`~django.db.models.Prefetch` object to further control
  919. the prefetch operation.
  920. In its simplest form ``Prefetch`` is equivalent to the traditional string based
  921. lookups:
  922. >>> from django.db.models import Prefetch
  923. >>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings'))
  924. You can provide a custom queryset with the optional ``queryset`` argument.
  925. This can be used to change the default ordering of the queryset:
  926. >>> Restaurant.objects.prefetch_related(
  927. ... Prefetch('pizzas__toppings', queryset=Toppings.objects.order_by('name')))
  928. Or to call :meth:`~django.db.models.query.QuerySet.select_related()` when
  929. applicable to reduce the number of queries even further:
  930. >>> Pizza.objects.prefetch_related(
  931. ... Prefetch('restaurants', queryset=Restaurant.objects.select_related('best_pizza')))
  932. You can also assign the prefetched result to a custom attribute with the optional
  933. ``to_attr`` argument. The result will be stored directly in a list.
  934. This allows prefetching the same relation multiple times with a different
  935. ``QuerySet``; for instance:
  936. >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)
  937. >>> Restaurant.objects.prefetch_related(
  938. ... Prefetch('pizzas', to_attr='menu'),
  939. ... Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'))
  940. Lookups created with custom ``to_attr`` can still be traversed as usual by other
  941. lookups:
  942. >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)
  943. >>> Restaurant.objects.prefetch_related(
  944. ... Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'),
  945. ... 'vegetarian_menu__toppings')
  946. Using ``to_attr`` is recommended when filtering down the prefetch result as it is
  947. less ambiguous than storing a filtered result in the related manager's cache:
  948. >>> queryset = Pizza.objects.filter(vegetarian=True)
  949. >>>
  950. >>> # Recommended:
  951. >>> restaurants = Restaurant.objects.prefetch_related(
  952. ... Prefetch('pizzas', queryset=queryset, to_attr='vegetarian_pizzas'))
  953. >>> vegetarian_pizzas = restaurants[0].vegetarian_pizzas
  954. >>>
  955. >>> # Not recommended:
  956. >>> restaurants = Restaurant.objects.prefetch_related(
  957. ... Prefetch('pizzas', queryset=queryset))
  958. >>> vegetarian_pizzas = restaurants[0].pizzas.all()
  959. Custom prefetching also works with single related relations like
  960. forward ``ForeignKey`` or ``OneToOneField``. Generally you'll want to use
  961. :meth:`select_related()` for these relations, but there are a number of cases
  962. where prefetching with a custom ``QuerySet`` is useful:
  963. * You want to use a ``QuerySet`` that performs further prefetching
  964. on related models.
  965. * You want to prefetch only a subset of the related objects.
  966. * You want to use performance optimization techniques like
  967. :meth:`deferred fields <defer()>`:
  968. >>> queryset = Pizza.objects.only('name')
  969. >>>
  970. >>> restaurants = Restaurant.objects.prefetch_related(
  971. ... Prefetch('best_pizza', queryset=queryset))
  972. When using multiple databases, ``Prefetch`` will respect your choice of
  973. database. If the inner query does not specify a database, it will use the
  974. database selected by the outer query. All of the following are valid::
  975. >>> # Both inner and outer queries will use the 'replica' database
  976. >>> Restaurant.objects.prefetch_related('pizzas__toppings').using('replica')
  977. >>> Restaurant.objects.prefetch_related(
  978. ... Prefetch('pizzas__toppings'),
  979. ... ).using('replica')
  980. >>>
  981. >>> # Inner will use the 'replica' database; outer will use 'default' database
  982. >>> Restaurant.objects.prefetch_related(
  983. ... Prefetch('pizzas__toppings', queryset=Toppings.objects.using('replica')),
  984. ... )
  985. >>>
  986. >>> # Inner will use 'replica' database; outer will use 'cold-storage' database
  987. >>> Restaurant.objects.prefetch_related(
  988. ... Prefetch('pizzas__toppings', queryset=Toppings.objects.using('replica')),
  989. ... ).using('cold-storage')
  990. .. note::
  991. The ordering of lookups matters.
  992. Take the following examples:
  993. >>> prefetch_related('pizzas__toppings', 'pizzas')
  994. This works even though it's unordered because ``'pizzas__toppings'``
  995. already contains all the needed information, therefore the second argument
  996. ``'pizzas'`` is actually redundant.
  997. >>> prefetch_related('pizzas__toppings', Prefetch('pizzas', queryset=Pizza.objects.all()))
  998. This will raise a ``ValueError`` because of the attempt to redefine the
  999. queryset of a previously seen lookup. Note that an implicit queryset was
  1000. created to traverse ``'pizzas'`` as part of the ``'pizzas__toppings'``
  1001. lookup.
  1002. >>> prefetch_related('pizza_list__toppings', Prefetch('pizzas', to_attr='pizza_list'))
  1003. This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't exist yet
  1004. when ``'pizza_list__toppings'`` is being processed.
  1005. This consideration is not limited to the use of ``Prefetch`` objects. Some
  1006. advanced techniques may require that the lookups be performed in a
  1007. specific order to avoid creating extra queries; therefore it's recommended
  1008. to always carefully order ``prefetch_related`` arguments.
  1009. ``extra()``
  1010. ~~~~~~~~~~~
  1011. .. method:: extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
  1012. Sometimes, the Django query syntax by itself can't easily express a complex
  1013. ``WHERE`` clause. For these edge cases, Django provides the ``extra()``
  1014. ``QuerySet`` modifier — a hook for injecting specific clauses into the SQL
  1015. generated by a ``QuerySet``.
  1016. .. admonition:: Use this method as a last resort
  1017. This is an old API that we aim to deprecate at some point in the future.
  1018. Use it only if you cannot express your query using other queryset methods.
  1019. If you do need to use it, please `file a ticket
  1020. <https://code.djangoproject.com/newticket>`_ using the `QuerySet.extra
  1021. keyword <https://code.djangoproject.com/query?status=assigned&status=new&keywords=~QuerySet.extra>`_
  1022. with your use case (please check the list of existing tickets first) so
  1023. that we can enhance the QuerySet API to allow removing ``extra()``. We are
  1024. no longer improving or fixing bugs for this method.
  1025. For example, this use of ``extra()``::
  1026. >>> qs.extra(
  1027. ... select={'val': "select col from sometable where othercol = %s"},
  1028. ... select_params=(someparam,),
  1029. ... )
  1030. is equivalent to::
  1031. >>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,)))
  1032. The main benefit of using :class:`~django.db.models.expressions.RawSQL` is
  1033. that you can set ``output_field`` if needed. The main downside is that if
  1034. you refer to some table alias of the queryset in the raw SQL, then it is
  1035. possible that Django might change that alias (for example, when the
  1036. queryset is used as a subquery in yet another query).
  1037. .. warning::
  1038. You should be very careful whenever you use ``extra()``. Every time you use
  1039. it, you should escape any parameters that the user can control by using
  1040. ``params`` in order to protect against SQL injection attacks.
  1041. You also must not quote placeholders in the SQL string. This example is
  1042. vulnerable to SQL injection because of the quotes around ``%s``:
  1043. .. code-block:: sql
  1044. SELECT col FROM sometable WHERE othercol = '%s' # unsafe!
  1045. You can read more about how Django's :ref:`SQL injection protection
  1046. <sql-injection-protection>` works.
  1047. By definition, these extra lookups may not be portable to different database
  1048. engines (because you're explicitly writing SQL code) and violate the DRY
  1049. principle, so you should avoid them if possible.
  1050. Specify one or more of ``params``, ``select``, ``where`` or ``tables``. None
  1051. of the arguments is required, but you should use at least one of them.
  1052. * ``select``
  1053. The ``select`` argument lets you put extra fields in the ``SELECT``
  1054. clause. It should be a dictionary mapping attribute names to SQL
  1055. clauses to use to calculate that attribute.
  1056. Example::
  1057. Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
  1058. As a result, each ``Entry`` object will have an extra attribute,
  1059. ``is_recent``, a boolean representing whether the entry's ``pub_date``
  1060. is greater than Jan. 1, 2006.
  1061. Django inserts the given SQL snippet directly into the ``SELECT``
  1062. statement, so the resulting SQL of the above example would be something like:
  1063. .. code-block:: sql
  1064. SELECT blog_entry.*, (pub_date > '2006-01-01') AS is_recent
  1065. FROM blog_entry;
  1066. The next example is more advanced; it does a subquery to give each
  1067. resulting ``Blog`` object an ``entry_count`` attribute, an integer count
  1068. of associated ``Entry`` objects::
  1069. Blog.objects.extra(
  1070. select={
  1071. 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
  1072. },
  1073. )
  1074. In this particular case, we're exploiting the fact that the query will
  1075. already contain the ``blog_blog`` table in its ``FROM`` clause.
  1076. The resulting SQL of the above example would be:
  1077. .. code-block:: sql
  1078. SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id) AS entry_count
  1079. FROM blog_blog;
  1080. Note that the parentheses required by most database engines around
  1081. subqueries are not required in Django's ``select`` clauses. Also note
  1082. that some database backends, such as some MySQL versions, don't support
  1083. subqueries.
  1084. In some rare cases, you might wish to pass parameters to the SQL
  1085. fragments in ``extra(select=...)``. For this purpose, use the
  1086. ``select_params`` parameter.
  1087. This will work, for example::
  1088. Blog.objects.extra(
  1089. select={'a': '%s', 'b': '%s'},
  1090. select_params=('one', 'two'),
  1091. )
  1092. If you need to use a literal ``%s`` inside your select string, use
  1093. the sequence ``%%s``.
  1094. * ``where`` / ``tables``
  1095. You can define explicit SQL ``WHERE`` clauses — perhaps to perform
  1096. non-explicit joins — by using ``where``. You can manually add tables to
  1097. the SQL ``FROM`` clause by using ``tables``.
  1098. ``where`` and ``tables`` both take a list of strings. All ``where``
  1099. parameters are "AND"ed to any other search criteria.
  1100. Example::
  1101. Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
  1102. ...translates (roughly) into the following SQL:
  1103. .. code-block:: sql
  1104. SELECT * FROM blog_entry WHERE (foo='a' OR bar='a') AND (baz='a')
  1105. Be careful when using the ``tables`` parameter if you're specifying
  1106. tables that are already used in the query. When you add extra tables
  1107. via the ``tables`` parameter, Django assumes you want that table
  1108. included an extra time, if it is already included. That creates a
  1109. problem, since the table name will then be given an alias. If a table
  1110. appears multiple times in an SQL statement, the second and subsequent
  1111. occurrences must use aliases so the database can tell them apart. If
  1112. you're referring to the extra table you added in the extra ``where``
  1113. parameter this is going to cause errors.
  1114. Normally you'll only be adding extra tables that don't already appear
  1115. in the query. However, if the case outlined above does occur, there are
  1116. a few solutions. First, see if you can get by without including the
  1117. extra table and use the one already in the query. If that isn't
  1118. possible, put your ``extra()`` call at the front of the queryset
  1119. construction so that your table is the first use of that table.
  1120. Finally, if all else fails, look at the query produced and rewrite your
  1121. ``where`` addition to use the alias given to your extra table. The
  1122. alias will be the same each time you construct the queryset in the same
  1123. way, so you can rely upon the alias name to not change.
  1124. * ``order_by``
  1125. If you need to order the resulting queryset using some of the new
  1126. fields or tables you have included via ``extra()`` use the ``order_by``
  1127. parameter to ``extra()`` and pass in a sequence of strings. These
  1128. strings should either be model fields (as in the normal
  1129. :meth:`order_by()` method on querysets), of the form
  1130. ``table_name.column_name`` or an alias for a column that you specified
  1131. in the ``select`` parameter to ``extra()``.
  1132. For example::
  1133. q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
  1134. q = q.extra(order_by = ['-is_recent'])
  1135. This would sort all the items for which ``is_recent`` is true to the
  1136. front of the result set (``True`` sorts before ``False`` in a
  1137. descending ordering).
  1138. This shows, by the way, that you can make multiple calls to ``extra()``
  1139. and it will behave as you expect (adding new constraints each time).
  1140. * ``params``
  1141. The ``where`` parameter described above may use standard Python
  1142. database string placeholders — ``'%s'`` to indicate parameters the
  1143. database engine should automatically quote. The ``params`` argument is
  1144. a list of any extra parameters to be substituted.
  1145. Example::
  1146. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
  1147. Always use ``params`` instead of embedding values directly into
  1148. ``where`` because ``params`` will ensure values are quoted correctly
  1149. according to your particular backend. For example, quotes will be
  1150. escaped correctly.
  1151. Bad::
  1152. Entry.objects.extra(where=["headline='Lennon'"])
  1153. Good::
  1154. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
  1155. .. warning::
  1156. If you are performing queries on MySQL, note that MySQL's silent type coercion
  1157. may cause unexpected results when mixing types. If you query on a string
  1158. type column, but with an integer value, MySQL will coerce the types of all values
  1159. in the table to an integer before performing the comparison. For example, if your
  1160. table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
  1161. both rows will match. To prevent this, perform the correct typecasting
  1162. before using the value in a query.
  1163. ``defer()``
  1164. ~~~~~~~~~~~
  1165. .. method:: defer(*fields)
  1166. In some complex data-modeling situations, your models might contain a lot of
  1167. fields, some of which could contain a lot of data (for example, text fields),
  1168. or require expensive processing to convert them to Python objects. If you are
  1169. using the results of a queryset in some situation where you don't know
  1170. if you need those particular fields when you initially fetch the data, you can
  1171. tell Django not to retrieve them from the database.
  1172. This is done by passing the names of the fields to not load to ``defer()``::
  1173. Entry.objects.defer("headline", "body")
  1174. A queryset that has deferred fields will still return model instances. Each
  1175. deferred field will be retrieved from the database if you access that field
  1176. (one at a time, not all the deferred fields at once).
  1177. .. note::
  1178. Deferred fields will not lazy-load like this from asynchronous code.
  1179. Instead, you will get a ``SynchronousOnlyOperation`` exception. If you are
  1180. writing asynchronous code, you should not try to access any fields that you
  1181. ``defer()``.
  1182. You can make multiple calls to ``defer()``. Each call adds new fields to the
  1183. deferred set::
  1184. # Defers both the body and headline fields.
  1185. Entry.objects.defer("body").filter(rating=5).defer("headline")
  1186. The order in which fields are added to the deferred set does not matter.
  1187. Calling ``defer()`` with a field name that has already been deferred is
  1188. harmless (the field will still be deferred).
  1189. You can defer loading of fields in related models (if the related models are
  1190. loading via :meth:`select_related()`) by using the standard double-underscore
  1191. notation to separate related fields::
  1192. Blog.objects.select_related().defer("entry__headline", "entry__body")
  1193. If you want to clear the set of deferred fields, pass ``None`` as a parameter
  1194. to ``defer()``::
  1195. # Load all fields immediately.
  1196. my_queryset.defer(None)
  1197. Some fields in a model won't be deferred, even if you ask for them. You can
  1198. never defer the loading of the primary key. If you are using
  1199. :meth:`select_related()` to retrieve related models, you shouldn't defer the
  1200. loading of the field that connects from the primary model to the related
  1201. one, doing so will result in an error.
  1202. .. note::
  1203. The ``defer()`` method (and its cousin, :meth:`only()`, below) are only for
  1204. advanced use-cases. They provide an optimization for when you have analyzed
  1205. your queries closely and understand *exactly* what information you need and
  1206. have measured that the difference between returning the fields you need and
  1207. the full set of fields for the model will be significant.
  1208. Even if you think you are in the advanced use-case situation, **only use**
  1209. ``defer()`` **when you cannot, at queryset load time, determine if you will
  1210. need the extra fields or not**. If you are frequently loading and using a
  1211. particular subset of your data, the best choice you can make is to
  1212. normalize your models and put the non-loaded data into a separate model
  1213. (and database table). If the columns *must* stay in the one table for some
  1214. reason, create a model with ``Meta.managed = False`` (see the
  1215. :attr:`managed attribute <django.db.models.Options.managed>` documentation)
  1216. containing just the fields you normally need to load and use that where you
  1217. might otherwise call ``defer()``. This makes your code more explicit to the
  1218. reader, is slightly faster and consumes a little less memory in the Python
  1219. process.
  1220. For example, both of these models use the same underlying database table::
  1221. class CommonlyUsedModel(models.Model):
  1222. f1 = models.CharField(max_length=10)
  1223. class Meta:
  1224. managed = False
  1225. db_table = 'app_largetable'
  1226. class ManagedModel(models.Model):
  1227. f1 = models.CharField(max_length=10)
  1228. f2 = models.CharField(max_length=10)
  1229. class Meta:
  1230. db_table = 'app_largetable'
  1231. # Two equivalent QuerySets:
  1232. CommonlyUsedModel.objects.all()
  1233. ManagedModel.objects.defer('f2')
  1234. If many fields need to be duplicated in the unmanaged model, it may be best
  1235. to create an abstract model with the shared fields and then have the
  1236. unmanaged and managed models inherit from the abstract model.
  1237. .. note::
  1238. When calling :meth:`~django.db.models.Model.save()` for instances with
  1239. deferred fields, only the loaded fields will be saved. See
  1240. :meth:`~django.db.models.Model.save()` for more details.
  1241. ``only()``
  1242. ~~~~~~~~~~
  1243. .. method:: only(*fields)
  1244. The ``only()`` method is essentially the opposite of :meth:`defer`. Only the
  1245. fields passed into this method and that are *not* already specified as deferred
  1246. are loaded immediately when the queryset is evaluated.
  1247. If you have a model where almost all the fields need to be deferred, using
  1248. ``only()`` to specify the complementary set of fields can result in simpler
  1249. code.
  1250. Suppose you have a model with fields ``name``, ``age`` and ``biography``. The
  1251. following two querysets are the same, in terms of deferred fields::
  1252. Person.objects.defer("age", "biography")
  1253. Person.objects.only("name")
  1254. Whenever you call ``only()`` it *replaces* the set of fields to load
  1255. immediately. The method's name is mnemonic: **only** those fields are loaded
  1256. immediately; the remainder are deferred. Thus, successive calls to ``only()``
  1257. result in only the final fields being considered::
  1258. # This will defer all fields except the headline.
  1259. Entry.objects.only("body", "rating").only("headline")
  1260. Since ``defer()`` acts incrementally (adding fields to the deferred list), you
  1261. can combine calls to ``only()`` and ``defer()`` and things will behave
  1262. logically::
  1263. # Final result is that everything except "headline" is deferred.
  1264. Entry.objects.only("headline", "body").defer("body")
  1265. # Final result loads headline immediately.
  1266. Entry.objects.defer("body").only("headline", "body")
  1267. All of the cautions in the note for the :meth:`defer` documentation apply to
  1268. ``only()`` as well. Use it cautiously and only after exhausting your other
  1269. options.
  1270. Using :meth:`only` and omitting a field requested using :meth:`select_related`
  1271. is an error as well.
  1272. As with ``defer()``, you cannot access the non-loaded fields from asynchronous
  1273. code and expect them to load. Instead, you will get a
  1274. ``SynchronousOnlyOperation`` exception. Ensure that all fields you might access
  1275. are in your ``only()`` call.
  1276. .. note::
  1277. When calling :meth:`~django.db.models.Model.save()` for instances with
  1278. deferred fields, only the loaded fields will be saved. See
  1279. :meth:`~django.db.models.Model.save()` for more details.
  1280. .. note::
  1281. When using :meth:`defer` after ``only()`` the fields in :meth:`defer` will
  1282. override ``only()`` for fields that are listed in both.
  1283. ``using()``
  1284. ~~~~~~~~~~~
  1285. .. method:: using(alias)
  1286. This method is for controlling which database the ``QuerySet`` will be
  1287. evaluated against if you are using more than one database. The only argument
  1288. this method takes is the alias of a database, as defined in
  1289. :setting:`DATABASES`.
  1290. For example::
  1291. # queries the database with the 'default' alias.
  1292. >>> Entry.objects.all()
  1293. # queries the database with the 'backup' alias
  1294. >>> Entry.objects.using('backup')
  1295. ``select_for_update()``
  1296. ~~~~~~~~~~~~~~~~~~~~~~~
  1297. .. method:: select_for_update(nowait=False, skip_locked=False, of=(), no_key=False)
  1298. Returns a queryset that will lock rows until the end of the transaction,
  1299. generating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases.
  1300. For example::
  1301. from django.db import transaction
  1302. entries = Entry.objects.select_for_update().filter(author=request.user)
  1303. with transaction.atomic():
  1304. for entry in entries:
  1305. ...
  1306. When the queryset is evaluated (``for entry in entries`` in this case), all
  1307. matched entries will be locked until the end of the transaction block, meaning
  1308. that other transactions will be prevented from changing or acquiring locks on
  1309. them.
  1310. Usually, if another transaction has already acquired a lock on one of the
  1311. selected rows, the query will block until the lock is released. If this is
  1312. not the behavior you want, call ``select_for_update(nowait=True)``. This will
  1313. make the call non-blocking. If a conflicting lock is already acquired by
  1314. another transaction, :exc:`~django.db.DatabaseError` will be raised when the
  1315. queryset is evaluated. You can also ignore locked rows by using
  1316. ``select_for_update(skip_locked=True)`` instead. The ``nowait`` and
  1317. ``skip_locked`` are mutually exclusive and attempts to call
  1318. ``select_for_update()`` with both options enabled will result in a
  1319. :exc:`ValueError`.
  1320. By default, ``select_for_update()`` locks all rows that are selected by the
  1321. query. For example, rows of related objects specified in :meth:`select_related`
  1322. are locked in addition to rows of the queryset's model. If this isn't desired,
  1323. specify the related objects you want to lock in ``select_for_update(of=(...))``
  1324. using the same fields syntax as :meth:`select_related`. Use the value ``'self'``
  1325. to refer to the queryset's model.
  1326. .. admonition:: Lock parents models in ``select_for_update(of=(...))``
  1327. If you want to lock parents models when using :ref:`multi-table inheritance
  1328. <multi-table-inheritance>`, you must specify parent link fields (by default
  1329. ``<parent_model_name>_ptr``) in the ``of`` argument. For example::
  1330. Restaurant.objects.select_for_update(of=('self', 'place_ptr'))
  1331. .. admonition:: Using ``select_for_update(of=(...))`` with specified fields
  1332. If you want to lock models and specify selected fields, e.g. using
  1333. :meth:`values`, you must select at least one field from each model in the
  1334. ``of`` argument. Models without selected fields will not be locked.
  1335. On PostgreSQL only, you can pass ``no_key=True`` in order to acquire a weaker
  1336. lock, that still allows creating rows that merely reference locked rows
  1337. (through a foreign key, for example) while the lock is in place. The
  1338. PostgreSQL documentation has more details about `row-level lock modes
  1339. <https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS>`_.
  1340. You can't use ``select_for_update()`` on nullable relations::
  1341. >>> Person.objects.select_related('hometown').select_for_update()
  1342. Traceback (most recent call last):
  1343. ...
  1344. django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join
  1345. To avoid that restriction, you can exclude null objects if you don't care about
  1346. them::
  1347. >>> Person.objects.select_related('hometown').select_for_update().exclude(hometown=None)
  1348. <QuerySet [<Person: ...)>, ...]>
  1349. The ``postgresql``, ``oracle``, and ``mysql`` database backends support
  1350. ``select_for_update()``. However, MariaDB only supports the ``nowait``
  1351. argument, MariaDB 10.6+ also supports the ``skip_locked`` argument, and MySQL
  1352. 8.0.1+ supports the ``nowait``, ``skip_locked``, and ``of`` arguments. The
  1353. ``no_key`` argument is only supported on PostgreSQL.
  1354. Passing ``nowait=True``, ``skip_locked=True``, ``no_key=True``, or ``of`` to
  1355. ``select_for_update()`` using database backends that do not support these
  1356. options, such as MySQL, raises a :exc:`~django.db.NotSupportedError`. This
  1357. prevents code from unexpectedly blocking.
  1358. Evaluating a queryset with ``select_for_update()`` in autocommit mode on
  1359. backends which support ``SELECT ... FOR UPDATE`` is a
  1360. :exc:`~django.db.transaction.TransactionManagementError` error because the
  1361. rows are not locked in that case. If allowed, this would facilitate data
  1362. corruption and could easily be caused by calling code that expects to be run in
  1363. a transaction outside of one.
  1364. Using ``select_for_update()`` on backends which do not support
  1365. ``SELECT ... FOR UPDATE`` (such as SQLite) will have no effect.
  1366. ``SELECT ... FOR UPDATE`` will not be added to the query, and an error isn't
  1367. raised if ``select_for_update()`` is used in autocommit mode.
  1368. .. warning::
  1369. Although ``select_for_update()`` normally fails in autocommit mode, since
  1370. :class:`~django.test.TestCase` automatically wraps each test in a
  1371. transaction, calling ``select_for_update()`` in a ``TestCase`` even outside
  1372. an :func:`~django.db.transaction.atomic()` block will (perhaps unexpectedly)
  1373. pass without raising a ``TransactionManagementError``. To properly test
  1374. ``select_for_update()`` you should use
  1375. :class:`~django.test.TransactionTestCase`.
  1376. .. admonition:: Certain expressions may not be supported
  1377. PostgreSQL doesn't support ``select_for_update()`` with
  1378. :class:`~django.db.models.expressions.Window` expressions.
  1379. ``raw()``
  1380. ~~~~~~~~~
  1381. .. method:: raw(raw_query, params=(), translations=None, using=None)
  1382. Takes a raw SQL query, executes it, and returns a
  1383. ``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
  1384. can be iterated over just like a normal ``QuerySet`` to provide object
  1385. instances.
  1386. See the :doc:`/topics/db/sql` for more information.
  1387. .. warning::
  1388. ``raw()`` always triggers a new query and doesn't account for previous
  1389. filtering. As such, it should generally be called from the ``Manager`` or
  1390. from a fresh ``QuerySet`` instance.
  1391. Operators that return new ``QuerySet``\s
  1392. ----------------------------------------
  1393. Combined querysets must use the same model.
  1394. AND (``&``)
  1395. ~~~~~~~~~~~
  1396. Combines two ``QuerySet``\s using the SQL ``AND`` operator.
  1397. The following are equivalent::
  1398. Model.objects.filter(x=1) & Model.objects.filter(y=2)
  1399. Model.objects.filter(x=1, y=2)
  1400. from django.db.models import Q
  1401. Model.objects.filter(Q(x=1) & Q(y=2))
  1402. SQL equivalent:
  1403. .. code-block:: sql
  1404. SELECT ... WHERE x=1 AND y=2
  1405. OR (``|``)
  1406. ~~~~~~~~~~
  1407. Combines two ``QuerySet``\s using the SQL ``OR`` operator.
  1408. The following are equivalent::
  1409. Model.objects.filter(x=1) | Model.objects.filter(y=2)
  1410. from django.db.models import Q
  1411. Model.objects.filter(Q(x=1) | Q(y=2))
  1412. SQL equivalent:
  1413. .. code-block:: sql
  1414. SELECT ... WHERE x=1 OR y=2
  1415. ``|`` is not a commutative operation, as different (though equivalent) queries
  1416. may be generated.
  1417. XOR (``^``)
  1418. ~~~~~~~~~~~
  1419. .. versionadded:: 4.1
  1420. Combines two ``QuerySet``\s using the SQL ``XOR`` operator.
  1421. The following are equivalent::
  1422. Model.objects.filter(x=1) ^ Model.objects.filter(y=2)
  1423. from django.db.models import Q
  1424. Model.objects.filter(Q(x=1) ^ Q(y=2))
  1425. SQL equivalent:
  1426. .. code-block:: sql
  1427. SELECT ... WHERE x=1 XOR y=2
  1428. .. note::
  1429. ``XOR`` is natively supported on MariaDB and MySQL. On other databases,
  1430. ``x ^ y ^ ... ^ z`` is converted to an equivalent:
  1431. .. code-block:: sql
  1432. (x OR y OR ... OR z) AND
  1433. 1=(
  1434. (CASE WHEN x THEN 1 ELSE 0 END) +
  1435. (CASE WHEN y THEN 1 ELSE 0 END) +
  1436. ...
  1437. (CASE WHEN z THEN 1 ELSE 0 END) +
  1438. )
  1439. Methods that do not return ``QuerySet``\s
  1440. -----------------------------------------
  1441. The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
  1442. something *other than* a ``QuerySet``.
  1443. These methods do not use a cache (see :ref:`caching-and-querysets`). Rather,
  1444. they query the database each time they're called.
  1445. Because these methods evaluate the QuerySet, they are blocking calls, and so
  1446. their main (synchronous) versions cannot be called from asynchronous code. For
  1447. this reason, each has a corresponding asynchronous version with an ``a`` prefix
  1448. - for example, rather than ``get(…)`` you can ``await aget(…)``.
  1449. There is usually no difference in behavior apart from their asynchronous
  1450. nature, but any differences are noted below next to each method.
  1451. .. versionchanged:: 4.1
  1452. The asynchronous versions of each method, prefixed with ``a`` was added.
  1453. ``get()``
  1454. ~~~~~~~~~
  1455. .. method:: get(*args, **kwargs)
  1456. .. method:: aget(*args, **kwargs)
  1457. *Asynchronous version*: ``aget()``
  1458. Returns the object matching the given lookup parameters, which should be in
  1459. the format described in `Field lookups`_. You should use lookups that are
  1460. guaranteed unique, such as the primary key or fields in a unique constraint.
  1461. For example::
  1462. Entry.objects.get(id=1)
  1463. Entry.objects.get(Q(blog=blog) & Q(entry_number=1))
  1464. If you expect a queryset to already return one row, you can use ``get()``
  1465. without any arguments to return the object for that row::
  1466. Entry.objects.filter(pk=1).get()
  1467. If ``get()`` doesn't find any object, it raises a :exc:`Model.DoesNotExist
  1468. <django.db.models.Model.DoesNotExist>` exception::
  1469. Entry.objects.get(id=-999) # raises Entry.DoesNotExist
  1470. If ``get()`` finds more than one object, it raises a
  1471. :exc:`Model.MultipleObjectsReturned
  1472. <django.db.models.Model.MultipleObjectsReturned>` exception::
  1473. Entry.objects.get(name='A Duplicated Name') # raises Entry.MultipleObjectsReturned
  1474. Both these exception classes are attributes of the model class, and specific to
  1475. that model. If you want to handle such exceptions from several ``get()`` calls
  1476. for different models, you can use their generic base classes. For example, you
  1477. can use :exc:`django.core.exceptions.ObjectDoesNotExist` to handle
  1478. :exc:`~django.db.models.Model.DoesNotExist` exceptions from multiple models::
  1479. from django.core.exceptions import ObjectDoesNotExist
  1480. try:
  1481. blog = Blog.objects.get(id=1)
  1482. entry = Entry.objects.get(blog=blog, entry_number=1)
  1483. except ObjectDoesNotExist:
  1484. print("Either the blog or entry doesn't exist.")
  1485. .. versionchanged:: 4.1
  1486. ``aget()`` method was added.
  1487. ``create()``
  1488. ~~~~~~~~~~~~
  1489. .. method:: create(**kwargs)
  1490. .. method:: acreate(*args, **kwargs)
  1491. *Asynchronous version*: ``acreate()``
  1492. A convenience method for creating an object and saving it all in one step. Thus::
  1493. p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
  1494. and::
  1495. p = Person(first_name="Bruce", last_name="Springsteen")
  1496. p.save(force_insert=True)
  1497. are equivalent.
  1498. The :ref:`force_insert <ref-models-force-insert>` parameter is documented
  1499. elsewhere, but all it means is that a new object will always be created.
  1500. Normally you won't need to worry about this. However, if your model contains a
  1501. manual primary key value that you set and if that value already exists in the
  1502. database, a call to ``create()`` will fail with an
  1503. :exc:`~django.db.IntegrityError` since primary keys must be unique. Be
  1504. prepared to handle the exception if you are using manual primary keys.
  1505. .. versionchanged:: 4.1
  1506. ``acreate()`` method was added.
  1507. ``get_or_create()``
  1508. ~~~~~~~~~~~~~~~~~~~
  1509. .. method:: get_or_create(defaults=None, **kwargs)
  1510. .. method:: aget_or_create(defaults=None, **kwargs)
  1511. *Asynchronous version*: ``aget_or_create()``
  1512. A convenience method for looking up an object with the given ``kwargs`` (may be
  1513. empty if your model has defaults for all fields), creating one if necessary.
  1514. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
  1515. created object and ``created`` is a boolean specifying whether a new object was
  1516. created.
  1517. This is meant to prevent duplicate objects from being created when requests are
  1518. made in parallel, and as a shortcut to boilerplatish code. For example::
  1519. try:
  1520. obj = Person.objects.get(first_name='John', last_name='Lennon')
  1521. except Person.DoesNotExist:
  1522. obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
  1523. obj.save()
  1524. Here, with concurrent requests, multiple attempts to save a ``Person`` with
  1525. the same parameters may be made. To avoid this race condition, the above
  1526. example can be rewritten using ``get_or_create()`` like so::
  1527. obj, created = Person.objects.get_or_create(
  1528. first_name='John',
  1529. last_name='Lennon',
  1530. defaults={'birthday': date(1940, 10, 9)},
  1531. )
  1532. Any keyword arguments passed to ``get_or_create()`` — *except* an optional one
  1533. called ``defaults`` — will be used in a :meth:`get()` call. If an object is
  1534. found, ``get_or_create()`` returns a tuple of that object and ``False``.
  1535. .. warning::
  1536. This method is atomic assuming that the database enforces uniqueness of the
  1537. keyword arguments (see :attr:`~django.db.models.Field.unique` or
  1538. :attr:`~django.db.models.Options.unique_together`). If the fields used in the
  1539. keyword arguments do not have a uniqueness constraint, concurrent calls to
  1540. this method may result in multiple rows with the same parameters being
  1541. inserted.
  1542. You can specify more complex conditions for the retrieved object by chaining
  1543. ``get_or_create()`` with ``filter()`` and using :class:`Q objects
  1544. <django.db.models.Q>`. For example, to retrieve Robert or Bob Marley if either
  1545. exists, and create the latter otherwise::
  1546. from django.db.models import Q
  1547. obj, created = Person.objects.filter(
  1548. Q(first_name='Bob') | Q(first_name='Robert'),
  1549. ).get_or_create(last_name='Marley', defaults={'first_name': 'Bob'})
  1550. If multiple objects are found, ``get_or_create()`` raises
  1551. :exc:`~django.core.exceptions.MultipleObjectsReturned`. If an object is *not*
  1552. found, ``get_or_create()`` will instantiate and save a new object, returning a
  1553. tuple of the new object and ``True``. The new object will be created roughly
  1554. according to this algorithm::
  1555. params = {k: v for k, v in kwargs.items() if '__' not in k}
  1556. params.update({k: v() if callable(v) else v for k, v in defaults.items()})
  1557. obj = self.model(**params)
  1558. obj.save()
  1559. In English, that means start with any non-``'defaults'`` keyword argument that
  1560. doesn't contain a double underscore (which would indicate a non-exact lookup).
  1561. Then add the contents of ``defaults``, overriding any keys if necessary, and
  1562. use the result as the keyword arguments to the model class. If there are any
  1563. callables in ``defaults``, evaluate them. As hinted at above, this is a
  1564. simplification of the algorithm that is used, but it contains all the pertinent
  1565. details. The internal implementation has some more error-checking than this and
  1566. handles some extra edge-conditions; if you're interested, read the code.
  1567. If you have a field named ``defaults`` and want to use it as an exact lookup in
  1568. ``get_or_create()``, use ``'defaults__exact'``, like so::
  1569. Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
  1570. The ``get_or_create()`` method has similar error behavior to :meth:`create()`
  1571. when you're using manually specified primary keys. If an object needs to be
  1572. created and the key already exists in the database, an
  1573. :exc:`~django.db.IntegrityError` will be raised.
  1574. Finally, a word on using ``get_or_create()`` in Django views. Please make sure
  1575. to use it only in ``POST`` requests unless you have a good reason not to.
  1576. ``GET`` requests shouldn't have any effect on data. Instead, use ``POST``
  1577. whenever a request to a page has a side effect on your data. For more, see
  1578. :rfc:`Safe methods <9110#section-9.2.1>` in the HTTP spec.
  1579. .. warning::
  1580. You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`
  1581. attributes and reverse relations. In that case you will restrict the queries
  1582. inside the context of that relation. That could lead you to some integrity
  1583. problems if you don't use it consistently.
  1584. Being the following models::
  1585. class Chapter(models.Model):
  1586. title = models.CharField(max_length=255, unique=True)
  1587. class Book(models.Model):
  1588. title = models.CharField(max_length=256)
  1589. chapters = models.ManyToManyField(Chapter)
  1590. You can use ``get_or_create()`` through Book's chapters field, but it only
  1591. fetches inside the context of that book::
  1592. >>> book = Book.objects.create(title="Ulysses")
  1593. >>> book.chapters.get_or_create(title="Telemachus")
  1594. (<Chapter: Telemachus>, True)
  1595. >>> book.chapters.get_or_create(title="Telemachus")
  1596. (<Chapter: Telemachus>, False)
  1597. >>> Chapter.objects.create(title="Chapter 1")
  1598. <Chapter: Chapter 1>
  1599. >>> book.chapters.get_or_create(title="Chapter 1")
  1600. # Raises IntegrityError
  1601. This is happening because it's trying to get or create "Chapter 1" through the
  1602. book "Ulysses", but it can't do any of them: the relation can't fetch that
  1603. chapter because it isn't related to that book, but it can't create it either
  1604. because ``title`` field should be unique.
  1605. .. versionchanged:: 4.1
  1606. ``aget_or_create()`` method was added.
  1607. ``update_or_create()``
  1608. ~~~~~~~~~~~~~~~~~~~~~~
  1609. .. method:: update_or_create(defaults=None, **kwargs)
  1610. .. method:: aupdate_or_create(defaults=None, **kwargs)
  1611. *Asynchronous version*: ``aupdate_or_create()``
  1612. A convenience method for updating an object with the given ``kwargs``, creating
  1613. a new one if necessary. The ``defaults`` is a dictionary of (field, value)
  1614. pairs used to update the object. The values in ``defaults`` can be callables.
  1615. Returns a tuple of ``(object, created)``, where ``object`` is the created or
  1616. updated object and ``created`` is a boolean specifying whether a new object was
  1617. created.
  1618. The ``update_or_create`` method tries to fetch an object from database based on
  1619. the given ``kwargs``. If a match is found, it updates the fields passed in the
  1620. ``defaults`` dictionary.
  1621. This is meant as a shortcut to boilerplatish code. For example::
  1622. defaults = {'first_name': 'Bob'}
  1623. try:
  1624. obj = Person.objects.get(first_name='John', last_name='Lennon')
  1625. for key, value in defaults.items():
  1626. setattr(obj, key, value)
  1627. obj.save()
  1628. except Person.DoesNotExist:
  1629. new_values = {'first_name': 'John', 'last_name': 'Lennon'}
  1630. new_values.update(defaults)
  1631. obj = Person(**new_values)
  1632. obj.save()
  1633. This pattern gets quite unwieldy as the number of fields in a model goes up.
  1634. The above example can be rewritten using ``update_or_create()`` like so::
  1635. obj, created = Person.objects.update_or_create(
  1636. first_name='John', last_name='Lennon',
  1637. defaults={'first_name': 'Bob'},
  1638. )
  1639. For a detailed description of how names passed in ``kwargs`` are resolved, see
  1640. :meth:`get_or_create`.
  1641. As described above in :meth:`get_or_create`, this method is prone to a
  1642. race-condition which can result in multiple rows being inserted simultaneously
  1643. if uniqueness is not enforced at the database level.
  1644. Like :meth:`get_or_create` and :meth:`create`, if you're using manually
  1645. specified primary keys and an object needs to be created but the key already
  1646. exists in the database, an :exc:`~django.db.IntegrityError` is raised.
  1647. .. versionchanged:: 4.1
  1648. ``aupdate_or_create()`` method was added.
  1649. .. versionchanged:: 4.2
  1650. In older versions, ``update_or_create()`` didn't specify ``update_fields``
  1651. when calling :meth:`Model.save() <django.db.models.Model.save>`.
  1652. ``bulk_create()``
  1653. ~~~~~~~~~~~~~~~~~
  1654. .. method:: bulk_create(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None)
  1655. .. method:: abulk_create(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None)
  1656. *Asynchronous version*: ``abulk_create()``
  1657. This method inserts the provided list of objects into the database in an
  1658. efficient manner (generally only 1 query, no matter how many objects there
  1659. are), and returns created objects as a list, in the same order as provided::
  1660. >>> objs = Entry.objects.bulk_create([
  1661. ... Entry(headline='This is a test'),
  1662. ... Entry(headline='This is only a test'),
  1663. ... ])
  1664. This has a number of caveats though:
  1665. * The model's ``save()`` method will not be called, and the ``pre_save`` and
  1666. ``post_save`` signals will not be sent.
  1667. * It does not work with child models in a multi-table inheritance scenario.
  1668. * If the model's primary key is an :class:`~django.db.models.AutoField`, the
  1669. primary key attribute can only be retrieved on certain databases (currently
  1670. PostgreSQL, MariaDB 10.5+, and SQLite 3.35+). On other databases, it will not
  1671. be set.
  1672. * It does not work with many-to-many relationships.
  1673. * It casts ``objs`` to a list, which fully evaluates ``objs`` if it's a
  1674. generator. The cast allows inspecting all objects so that any objects with a
  1675. manually set primary key can be inserted first. If you want to insert objects
  1676. in batches without evaluating the entire generator at once, you can use this
  1677. technique as long as the objects don't have any manually set primary keys::
  1678. from itertools import islice
  1679. batch_size = 100
  1680. objs = (Entry(headline='Test %s' % i) for i in range(1000))
  1681. while True:
  1682. batch = list(islice(objs, batch_size))
  1683. if not batch:
  1684. break
  1685. Entry.objects.bulk_create(batch, batch_size)
  1686. The ``batch_size`` parameter controls how many objects are created in a single
  1687. query. The default is to create all objects in one batch, except for SQLite
  1688. where the default is such that at most 999 variables per query are used.
  1689. On databases that support it (all but Oracle), setting the ``ignore_conflicts``
  1690. parameter to ``True`` tells the database to ignore failure to insert any rows
  1691. that fail constraints such as duplicate unique values.
  1692. On databases that support it (all except Oracle and SQLite < 3.24), setting the
  1693. ``update_conflicts`` parameter to ``True``, tells the database to update
  1694. ``update_fields`` when a row insertion fails on conflicts. On PostgreSQL and
  1695. SQLite, in addition to ``update_fields``, a list of ``unique_fields`` that may
  1696. be in conflict must be provided.
  1697. Enabling the ``ignore_conflicts`` or ``update_conflicts`` parameter disable
  1698. setting the primary key on each model instance (if the database normally
  1699. support it).
  1700. .. warning::
  1701. On MySQL and MariaDB, setting the ``ignore_conflicts`` parameter to
  1702. ``True`` turns certain types of errors, other than duplicate key, into
  1703. warnings. Even with Strict Mode. For example: invalid values or
  1704. non-nullable violations. See the `MySQL documentation`_ and
  1705. `MariaDB documentation`_ for more details.
  1706. .. _MySQL documentation: https://dev.mysql.com/doc/refman/en/sql-mode.html#ignore-strict-comparison
  1707. .. _MariaDB documentation: https://mariadb.com/kb/en/ignore/
  1708. .. versionchanged:: 4.1
  1709. The ``update_conflicts``, ``update_fields``, and ``unique_fields``
  1710. parameters were added to support updating fields when a row insertion fails
  1711. on conflict.
  1712. ``abulk_create()`` method was added.
  1713. ``bulk_update()``
  1714. ~~~~~~~~~~~~~~~~~
  1715. .. method:: bulk_update(objs, fields, batch_size=None)
  1716. .. method:: abulk_update(objs, fields, batch_size=None)
  1717. *Asynchronous version*: ``abulk_update()``
  1718. This method efficiently updates the given fields on the provided model
  1719. instances, generally with one query, and returns the number of objects
  1720. updated::
  1721. >>> objs = [
  1722. ... Entry.objects.create(headline='Entry 1'),
  1723. ... Entry.objects.create(headline='Entry 2'),
  1724. ... ]
  1725. >>> objs[0].headline = 'This is entry 1'
  1726. >>> objs[1].headline = 'This is entry 2'
  1727. >>> Entry.objects.bulk_update(objs, ['headline'])
  1728. 2
  1729. :meth:`.QuerySet.update` is used to save the changes, so this is more efficient
  1730. than iterating through the list of models and calling ``save()`` on each of
  1731. them, but it has a few caveats:
  1732. * You cannot update the model's primary key.
  1733. * Each model's ``save()`` method isn't called, and the
  1734. :attr:`~django.db.models.signals.pre_save` and
  1735. :attr:`~django.db.models.signals.post_save` signals aren't sent.
  1736. * If updating a large number of columns in a large number of rows, the SQL
  1737. generated can be very large. Avoid this by specifying a suitable
  1738. ``batch_size``.
  1739. * Updating fields defined on multi-table inheritance ancestors will incur an
  1740. extra query per ancestor.
  1741. * When an individual batch contains duplicates, only the first instance in that
  1742. batch will result in an update.
  1743. * The number of objects updated returned by the function may be fewer than the
  1744. number of objects passed in. This can be due to duplicate objects passed in
  1745. which are updated in the same batch or race conditions such that objects are
  1746. no longer present in the database.
  1747. The ``batch_size`` parameter controls how many objects are saved in a single
  1748. query. The default is to update all objects in one batch, except for SQLite
  1749. and Oracle which have restrictions on the number of variables used in a query.
  1750. .. versionchanged:: 4.1
  1751. ``abulk_update()`` method was added.
  1752. ``count()``
  1753. ~~~~~~~~~~~
  1754. .. method:: count()
  1755. .. method:: acount()
  1756. *Asynchronous version*: ``acount()``
  1757. Returns an integer representing the number of objects in the database matching
  1758. the ``QuerySet``.
  1759. Example::
  1760. # Returns the total number of entries in the database.
  1761. Entry.objects.count()
  1762. # Returns the number of entries whose headline contains 'Lennon'
  1763. Entry.objects.filter(headline__contains='Lennon').count()
  1764. A ``count()`` call performs a ``SELECT COUNT(*)`` behind the scenes, so you
  1765. should always use ``count()`` rather than loading all of the record into Python
  1766. objects and calling ``len()`` on the result (unless you need to load the
  1767. objects into memory anyway, in which case ``len()`` will be faster).
  1768. Note that if you want the number of items in a ``QuerySet`` and are also
  1769. retrieving model instances from it (for example, by iterating over it), it's
  1770. probably more efficient to use ``len(queryset)`` which won't cause an extra
  1771. database query like ``count()`` would.
  1772. If the queryset has already been fully retrieved, ``count()`` will use that
  1773. length rather than perform an extra database query.
  1774. .. versionchanged:: 4.1
  1775. ``acount()`` method was added.
  1776. ``in_bulk()``
  1777. ~~~~~~~~~~~~~
  1778. .. method:: in_bulk(id_list=None, *, field_name='pk')
  1779. .. method:: ain_bulk(id_list=None, *, field_name='pk')
  1780. *Asynchronous version*: ``ain_bulk()``
  1781. Takes a list of field values (``id_list``) and the ``field_name`` for those
  1782. values, and returns a dictionary mapping each value to an instance of the
  1783. object with the given field value. No
  1784. :exc:`django.core.exceptions.ObjectDoesNotExist` exceptions will ever be raised
  1785. by ``in_bulk``; that is, any ``id_list`` value not matching any instance will
  1786. simply be ignored. If ``id_list`` isn't provided, all objects
  1787. in the queryset are returned. ``field_name`` must be a unique field or a
  1788. distinct field (if there's only one field specified in :meth:`distinct`).
  1789. ``field_name`` defaults to the primary key.
  1790. Example::
  1791. >>> Blog.objects.in_bulk([1])
  1792. {1: <Blog: Beatles Blog>}
  1793. >>> Blog.objects.in_bulk([1, 2])
  1794. {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
  1795. >>> Blog.objects.in_bulk([])
  1796. {}
  1797. >>> Blog.objects.in_bulk()
  1798. {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}
  1799. >>> Blog.objects.in_bulk(['beatles_blog'], field_name='slug')
  1800. {'beatles_blog': <Blog: Beatles Blog>}
  1801. >>> Blog.objects.distinct('name').in_bulk(field_name='name')
  1802. {'Beatles Blog': <Blog: Beatles Blog>, 'Cheddar Talk': <Blog: Cheddar Talk>, 'Django Weblog': <Blog: Django Weblog>}
  1803. If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
  1804. .. versionchanged:: 4.1
  1805. ``ain_bulk()`` method was added.
  1806. ``iterator()``
  1807. ~~~~~~~~~~~~~~
  1808. .. method:: iterator(chunk_size=None)
  1809. .. method:: aiterator(chunk_size=None)
  1810. *Asynchronous version*: ``aiterator()``
  1811. Evaluates the ``QuerySet`` (by performing the query) and returns an iterator
  1812. (see :pep:`234`) over the results, or an asynchronous iterator (see :pep:`492`)
  1813. if you call its asynchronous version ``aiterator``.
  1814. A ``QuerySet`` typically caches its results internally so that repeated
  1815. evaluations do not result in additional queries. In contrast, ``iterator()``
  1816. will read results directly, without doing any caching at the ``QuerySet`` level
  1817. (internally, the default iterator calls ``iterator()`` and caches the return
  1818. value). For a ``QuerySet`` which returns a large number of objects that you
  1819. only need to access once, this can result in better performance and a
  1820. significant reduction in memory.
  1821. Note that using ``iterator()`` on a ``QuerySet`` which has already been
  1822. evaluated will force it to evaluate again, repeating the query.
  1823. ``iterator()`` is compatible with previous calls to ``prefetch_related()`` as
  1824. long as ``chunk_size`` is given. Larger values will necessitate fewer queries
  1825. to accomplish the prefetching at the cost of greater memory usage.
  1826. .. note::
  1827. ``aiterator()`` is *not* compatible with previous calls to
  1828. ``prefetch_related()``.
  1829. On some databases (e.g. Oracle, `SQLite
  1830. <https://www.sqlite.org/limits.html#max_variable_number>`_), the maximum number
  1831. of terms in an SQL ``IN`` clause might be limited. Hence values below this
  1832. limit should be used. (In particular, when prefetching across two or more
  1833. relations, a ``chunk_size`` should be small enough that the anticipated number
  1834. of results for each prefetched relation still falls below the limit.)
  1835. So long as the QuerySet does not prefetch any related objects, providing no
  1836. value for ``chunk_size`` will result in Django using an implicit default of
  1837. 2000.
  1838. Depending on the database backend, query results will either be loaded all at
  1839. once or streamed from the database using server-side cursors.
  1840. .. versionchanged:: 4.1
  1841. Support for prefetching related objects was added to ``iterator()``.
  1842. ``aiterator()`` method was added.
  1843. .. deprecated:: 4.1
  1844. Using ``iterator()`` on a queryset that prefetches related objects without
  1845. providing the ``chunk_size`` is deprecated. In Django 5.0, an exception
  1846. will be raise.
  1847. With server-side cursors
  1848. ^^^^^^^^^^^^^^^^^^^^^^^^
  1849. Oracle and :ref:`PostgreSQL <postgresql-server-side-cursors>` use server-side
  1850. cursors to stream results from the database without loading the entire result
  1851. set into memory.
  1852. The Oracle database driver always uses server-side cursors.
  1853. With server-side cursors, the ``chunk_size`` parameter specifies the number of
  1854. results to cache at the database driver level. Fetching bigger chunks
  1855. diminishes the number of round trips between the database driver and the
  1856. database, at the expense of memory.
  1857. On PostgreSQL, server-side cursors will only be used when the
  1858. :setting:`DISABLE_SERVER_SIDE_CURSORS <DATABASE-DISABLE_SERVER_SIDE_CURSORS>`
  1859. setting is ``False``. Read :ref:`transaction-pooling-server-side-cursors` if
  1860. you're using a connection pooler configured in transaction pooling mode. When
  1861. server-side cursors are disabled, the behavior is the same as databases that
  1862. don't support server-side cursors.
  1863. Without server-side cursors
  1864. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1865. MySQL doesn't support streaming results, hence the Python database driver loads
  1866. the entire result set into memory. The result set is then transformed into
  1867. Python row objects by the database adapter using the ``fetchmany()`` method
  1868. defined in :pep:`249`.
  1869. SQLite can fetch results in batches using ``fetchmany()``, but since SQLite
  1870. doesn't provide isolation between queries within a connection, be careful when
  1871. writing to the table being iterated over. See :ref:`sqlite-isolation` for
  1872. more information.
  1873. The ``chunk_size`` parameter controls the size of batches Django retrieves from
  1874. the database driver. Larger batches decrease the overhead of communicating with
  1875. the database driver at the expense of a slight increase in memory consumption.
  1876. So long as the QuerySet does not prefetch any related objects, providing no
  1877. value for ``chunk_size`` will result in Django using an implicit default of
  1878. 2000, a value derived from `a calculation on the psycopg mailing list
  1879. <https://www.postgresql.org/message-id/4D2F2C71.8080805%40dndg.it>`_:
  1880. Assuming rows of 10-20 columns with a mix of textual and numeric data, 2000
  1881. is going to fetch less than 100KB of data, which seems a good compromise
  1882. between the number of rows transferred and the data discarded if the loop
  1883. is exited early.
  1884. ``latest()``
  1885. ~~~~~~~~~~~~
  1886. .. method:: latest(*fields)
  1887. .. method:: alatest(*fields)
  1888. *Asynchronous version*: ``alatest()``
  1889. Returns the latest object in the table based on the given field(s).
  1890. This example returns the latest ``Entry`` in the table, according to the
  1891. ``pub_date`` field::
  1892. Entry.objects.latest('pub_date')
  1893. You can also choose the latest based on several fields. For example, to select
  1894. the ``Entry`` with the earliest ``expire_date`` when two entries have the same
  1895. ``pub_date``::
  1896. Entry.objects.latest('pub_date', '-expire_date')
  1897. The negative sign in ``'-expire_date'`` means to sort ``expire_date`` in
  1898. *descending* order. Since ``latest()`` gets the last result, the ``Entry`` with
  1899. the earliest ``expire_date`` is selected.
  1900. If your model's :ref:`Meta <meta-options>` specifies
  1901. :attr:`~django.db.models.Options.get_latest_by`, you can omit any arguments to
  1902. ``earliest()`` or ``latest()``. The fields specified in
  1903. :attr:`~django.db.models.Options.get_latest_by` will be used by default.
  1904. Like :meth:`get()`, ``earliest()`` and ``latest()`` raise
  1905. :exc:`~django.db.models.Model.DoesNotExist` if there is no object with the
  1906. given parameters.
  1907. Note that ``earliest()`` and ``latest()`` exist purely for convenience and
  1908. readability.
  1909. .. admonition:: ``earliest()`` and ``latest()`` may return instances with null dates.
  1910. Since ordering is delegated to the database, results on fields that allow
  1911. null values may be ordered differently if you use different databases. For
  1912. example, PostgreSQL and MySQL sort null values as if they are higher than
  1913. non-null values, while SQLite does the opposite.
  1914. You may want to filter out null values::
  1915. Entry.objects.filter(pub_date__isnull=False).latest('pub_date')
  1916. .. versionchanged:: 4.1
  1917. ``alatest()`` method was added.
  1918. ``earliest()``
  1919. ~~~~~~~~~~~~~~
  1920. .. method:: earliest(*fields)
  1921. .. method:: aearliest(*fields)
  1922. *Asynchronous version*: ``aearliest()``
  1923. Works otherwise like :meth:`~django.db.models.query.QuerySet.latest` except
  1924. the direction is changed.
  1925. .. versionchanged:: 4.1
  1926. ``aearliest()`` method was added.
  1927. ``first()``
  1928. ~~~~~~~~~~~
  1929. .. method:: first()
  1930. .. method:: afirst()
  1931. *Asynchronous version*: ``afirst()``
  1932. Returns the first object matched by the queryset, or ``None`` if there
  1933. is no matching object. If the ``QuerySet`` has no ordering defined, then the
  1934. queryset is automatically ordered by the primary key. This can affect
  1935. aggregation results as described in :ref:`aggregation-ordering-interaction`.
  1936. Example::
  1937. p = Article.objects.order_by('title', 'pub_date').first()
  1938. Note that ``first()`` is a convenience method, the following code sample is
  1939. equivalent to the above example::
  1940. try:
  1941. p = Article.objects.order_by('title', 'pub_date')[0]
  1942. except IndexError:
  1943. p = None
  1944. .. versionchanged:: 4.1
  1945. ``afirst()`` method was added.
  1946. ``last()``
  1947. ~~~~~~~~~~
  1948. .. method:: last()
  1949. .. method:: alast()
  1950. *Asynchronous version*: ``alast()``
  1951. Works like :meth:`first()`, but returns the last object in the queryset.
  1952. .. versionchanged:: 4.1
  1953. ``alast()`` method was added.
  1954. ``aggregate()``
  1955. ~~~~~~~~~~~~~~~
  1956. .. method:: aggregate(*args, **kwargs)
  1957. .. method:: aaggregate(*args, **kwargs)
  1958. *Asynchronous version*: ``aaggregate()``
  1959. Returns a dictionary of aggregate values (averages, sums, etc.) calculated over
  1960. the ``QuerySet``. Each argument to ``aggregate()`` specifies a value that will
  1961. be included in the dictionary that is returned.
  1962. The aggregation functions that are provided by Django are described in
  1963. `Aggregation Functions`_ below. Since aggregates are also :doc:`query
  1964. expressions </ref/models/expressions>`, you may combine aggregates with other
  1965. aggregates or values to create complex aggregates.
  1966. Aggregates specified using keyword arguments will use the keyword as the name
  1967. for the annotation. Anonymous arguments will have a name generated for them
  1968. based upon the name of the aggregate function and the model field that is being
  1969. aggregated. Complex aggregates cannot use anonymous arguments and must specify
  1970. a keyword argument as an alias.
  1971. For example, when you are working with blog entries, you may want to know the
  1972. number of authors that have contributed blog entries::
  1973. >>> from django.db.models import Count
  1974. >>> q = Blog.objects.aggregate(Count('entry'))
  1975. {'entry__count': 16}
  1976. By using a keyword argument to specify the aggregate function, you can
  1977. control the name of the aggregation value that is returned::
  1978. >>> q = Blog.objects.aggregate(number_of_entries=Count('entry'))
  1979. {'number_of_entries': 16}
  1980. For an in-depth discussion of aggregation, see :doc:`the topic guide on
  1981. Aggregation </topics/db/aggregation>`.
  1982. .. versionchanged:: 4.1
  1983. ``aaggregate()`` method was added.
  1984. ``exists()``
  1985. ~~~~~~~~~~~~
  1986. .. method:: exists()
  1987. .. method:: aexists()
  1988. *Asynchronous version*: ``aexists()``
  1989. Returns ``True`` if the :class:`.QuerySet` contains any results, and ``False``
  1990. if not. This tries to perform the query in the simplest and fastest way
  1991. possible, but it *does* execute nearly the same query as a normal
  1992. :class:`.QuerySet` query.
  1993. :meth:`~.QuerySet.exists` is useful for searches relating to the existence of
  1994. any objects in a :class:`.QuerySet`, particularly in the context of a large
  1995. :class:`.QuerySet`.
  1996. To find whether a queryset contains any items::
  1997. if some_queryset.exists():
  1998. print("There is at least one object in some_queryset")
  1999. Which will be faster than::
  2000. if some_queryset:
  2001. print("There is at least one object in some_queryset")
  2002. ... but not by a large degree (hence needing a large queryset for efficiency
  2003. gains).
  2004. Additionally, if a ``some_queryset`` has not yet been evaluated, but you know
  2005. that it will be at some point, then using ``some_queryset.exists()`` will do
  2006. more overall work (one query for the existence check plus an extra one to later
  2007. retrieve the results) than using ``bool(some_queryset)``, which retrieves the
  2008. results and then checks if any were returned.
  2009. .. versionchanged:: 4.1
  2010. ``aexists()`` method was added.
  2011. ``contains()``
  2012. ~~~~~~~~~~~~~~
  2013. .. method:: contains(obj)
  2014. .. method:: acontains(obj)
  2015. *Asynchronous version*: ``acontains()``
  2016. Returns ``True`` if the :class:`.QuerySet` contains ``obj``, and ``False`` if
  2017. not. This tries to perform the query in the simplest and fastest way possible.
  2018. :meth:`contains` is useful for checking an object membership in a
  2019. :class:`.QuerySet`, particularly in the context of a large :class:`.QuerySet`.
  2020. To check whether a queryset contains a specific item::
  2021. if some_queryset.contains(obj):
  2022. print('Entry contained in queryset')
  2023. This will be faster than the following which requires evaluating and iterating
  2024. through the entire queryset::
  2025. if obj in some_queryset:
  2026. print('Entry contained in queryset')
  2027. Like :meth:`exists`, if ``some_queryset`` has not yet been evaluated, but you
  2028. know that it will be at some point, then using ``some_queryset.contains(obj)``
  2029. will make an additional database query, generally resulting in slower overall
  2030. performance.
  2031. .. versionchanged:: 4.1
  2032. ``acontains()`` method was added.
  2033. ``update()``
  2034. ~~~~~~~~~~~~
  2035. .. method:: update(**kwargs)
  2036. .. method:: aupdate(**kwargs)
  2037. *Asynchronous version*: ``aupdate()``
  2038. Performs an SQL update query for the specified fields, and returns
  2039. the number of rows matched (which may not be equal to the number of rows
  2040. updated if some rows already have the new value).
  2041. For example, to turn comments off for all blog entries published in 2010,
  2042. you could do this::
  2043. >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
  2044. (This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.)
  2045. You can update multiple fields — there's no limit on how many. For example,
  2046. here we update the ``comments_on`` and ``headline`` fields::
  2047. >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False, headline='This is old')
  2048. The ``update()`` method is applied instantly, and the only restriction on the
  2049. :class:`.QuerySet` that is updated is that it can only update columns in the
  2050. model's main table, not on related models. You can't do this, for example::
  2051. >>> Entry.objects.update(blog__name='foo') # Won't work!
  2052. Filtering based on related fields is still possible, though::
  2053. >>> Entry.objects.filter(blog__id=1).update(comments_on=True)
  2054. You cannot call ``update()`` on a :class:`.QuerySet` that has had a slice taken
  2055. or can otherwise no longer be filtered.
  2056. The ``update()`` method returns the number of affected rows::
  2057. >>> Entry.objects.filter(id=64).update(comments_on=True)
  2058. 1
  2059. >>> Entry.objects.filter(slug='nonexistent-slug').update(comments_on=True)
  2060. 0
  2061. >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
  2062. 132
  2063. If you're just updating a record and don't need to do anything with the model
  2064. object, the most efficient approach is to call ``update()``, rather than
  2065. loading the model object into memory. For example, instead of doing this::
  2066. e = Entry.objects.get(id=10)
  2067. e.comments_on = False
  2068. e.save()
  2069. ...do this::
  2070. Entry.objects.filter(id=10).update(comments_on=False)
  2071. Using ``update()`` also prevents a race condition wherein something might
  2072. change in your database in the short period of time between loading the object
  2073. and calling ``save()``.
  2074. Finally, realize that ``update()`` does an update at the SQL level and, thus,
  2075. does not call any ``save()`` methods on your models, nor does it emit the
  2076. :attr:`~django.db.models.signals.pre_save` or
  2077. :attr:`~django.db.models.signals.post_save` signals (which are a consequence of
  2078. calling :meth:`Model.save() <django.db.models.Model.save>`). If you want to
  2079. update a bunch of records for a model that has a custom
  2080. :meth:`~django.db.models.Model.save()` method, loop over them and call
  2081. :meth:`~django.db.models.Model.save()`, like this::
  2082. for e in Entry.objects.filter(pub_date__year=2010):
  2083. e.comments_on = False
  2084. e.save()
  2085. .. versionchanged:: 4.1
  2086. ``aupdate()`` method was added.
  2087. Ordered queryset
  2088. ^^^^^^^^^^^^^^^^
  2089. Chaining ``order_by()`` with ``update()`` is supported only on MariaDB and
  2090. MySQL, and is ignored for different databases. This is useful for updating a
  2091. unique field in the order that is specified without conflicts. For example::
  2092. Entry.objects.order_by('-number').update(number=F('number') + 1)
  2093. .. note::
  2094. ``order_by()`` clause will be ignored if it contains annotations, inherited
  2095. fields, or lookups spanning relations.
  2096. ``delete()``
  2097. ~~~~~~~~~~~~
  2098. .. method:: delete()
  2099. .. method:: adelete()
  2100. *Asynchronous version*: ``adelete()``
  2101. Performs an SQL delete query on all rows in the :class:`.QuerySet` and
  2102. returns the number of objects deleted and a dictionary with the number of
  2103. deletions per object type.
  2104. The ``delete()`` is applied instantly. You cannot call ``delete()`` on a
  2105. :class:`.QuerySet` that has had a slice taken or can otherwise no longer be
  2106. filtered.
  2107. For example, to delete all the entries in a particular blog::
  2108. >>> b = Blog.objects.get(pk=1)
  2109. # Delete all the entries belonging to this Blog.
  2110. >>> Entry.objects.filter(blog=b).delete()
  2111. (4, {'blog.Entry': 2, 'blog.Entry_authors': 2})
  2112. By default, Django's :class:`~django.db.models.ForeignKey` emulates the SQL
  2113. constraint ``ON DELETE CASCADE`` — in other words, any objects with foreign
  2114. keys pointing at the objects to be deleted will be deleted along with them.
  2115. For example::
  2116. >>> blogs = Blog.objects.all()
  2117. # This will delete all Blogs and all of their Entry objects.
  2118. >>> blogs.delete()
  2119. (5, {'blog.Blog': 1, 'blog.Entry': 2, 'blog.Entry_authors': 2})
  2120. This cascade behavior is customizable via the
  2121. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  2122. :class:`~django.db.models.ForeignKey`.
  2123. The ``delete()`` method does a bulk delete and does not call any ``delete()``
  2124. methods on your models. It does, however, emit the
  2125. :data:`~django.db.models.signals.pre_delete` and
  2126. :data:`~django.db.models.signals.post_delete` signals for all deleted objects
  2127. (including cascaded deletions).
  2128. Django needs to fetch objects into memory to send signals and handle cascades.
  2129. However, if there are no cascades and no signals, then Django may take a
  2130. fast-path and delete objects without fetching into memory. For large
  2131. deletes this can result in significantly reduced memory usage. The amount of
  2132. executed queries can be reduced, too.
  2133. ForeignKeys which are set to :attr:`~django.db.models.ForeignKey.on_delete`
  2134. ``DO_NOTHING`` do not prevent taking the fast-path in deletion.
  2135. Note that the queries generated in object deletion is an implementation
  2136. detail subject to change.
  2137. .. versionchanged:: 4.1
  2138. ``adelete()`` method was added.
  2139. ``as_manager()``
  2140. ~~~~~~~~~~~~~~~~
  2141. .. classmethod:: as_manager()
  2142. Class method that returns an instance of :class:`~django.db.models.Manager`
  2143. with a copy of the ``QuerySet``’s methods. See
  2144. :ref:`create-manager-with-queryset-methods` for more details.
  2145. Note that unlike the other entries in this section, this does not have an
  2146. asynchronous variant as it does not execute a query.
  2147. ``explain()``
  2148. ~~~~~~~~~~~~~
  2149. .. method:: explain(format=None, **options)
  2150. .. method:: aexplain(format=None, **options)
  2151. *Asynchronous version*: ``aexplain()``
  2152. Returns a string of the ``QuerySet``’s execution plan, which details how the
  2153. database would execute the query, including any indexes or joins that would be
  2154. used. Knowing these details may help you improve the performance of slow
  2155. queries.
  2156. For example, when using PostgreSQL::
  2157. >>> print(Blog.objects.filter(title='My Blog').explain())
  2158. Seq Scan on blog (cost=0.00..35.50 rows=10 width=12)
  2159. Filter: (title = 'My Blog'::bpchar)
  2160. The output differs significantly between databases.
  2161. ``explain()`` is supported by all built-in database backends except Oracle
  2162. because an implementation there isn't straightforward.
  2163. The ``format`` parameter changes the output format from the databases's
  2164. default, which is usually text-based. PostgreSQL supports ``'TEXT'``,
  2165. ``'JSON'``, ``'YAML'``, and ``'XML'`` formats. MariaDB and MySQL support
  2166. ``'TEXT'`` (also called ``'TRADITIONAL'``) and ``'JSON'`` formats. MySQL
  2167. 8.0.16+ also supports an improved ``'TREE'`` format, which is similar to
  2168. PostgreSQL's ``'TEXT'`` output and is used by default, if supported.
  2169. Some databases accept flags that can return more information about the query.
  2170. Pass these flags as keyword arguments. For example, when using PostgreSQL::
  2171. >>> print(Blog.objects.filter(title='My Blog').explain(verbose=True, analyze=True))
  2172. Seq Scan on public.blog (cost=0.00..35.50 rows=10 width=12) (actual time=0.004..0.004 rows=10 loops=1)
  2173. Output: id, title
  2174. Filter: (blog.title = 'My Blog'::bpchar)
  2175. Planning time: 0.064 ms
  2176. Execution time: 0.058 ms
  2177. On some databases, flags may cause the query to be executed which could have
  2178. adverse effects on your database. For example, the ``ANALYZE`` flag supported
  2179. by MariaDB, MySQL 8.0.18+, and PostgreSQL could result in changes to data if
  2180. there are triggers or if a function is called, even for a ``SELECT`` query.
  2181. .. versionchanged:: 4.1
  2182. ``aexplain()`` method was added.
  2183. .. _field-lookups:
  2184. ``Field`` lookups
  2185. -----------------
  2186. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
  2187. specified as keyword arguments to the ``QuerySet`` methods :meth:`filter()`,
  2188. :meth:`exclude()` and :meth:`get()`.
  2189. For an introduction, see :ref:`models and database queries documentation
  2190. <field-lookups-intro>`.
  2191. Django's built-in lookups are listed below. It is also possible to write
  2192. :doc:`custom lookups </howto/custom-lookups>` for model fields.
  2193. As a convenience when no lookup type is provided (like in
  2194. ``Entry.objects.get(id=14)``) the lookup type is assumed to be :lookup:`exact`.
  2195. .. fieldlookup:: exact
  2196. ``exact``
  2197. ~~~~~~~~~
  2198. Exact match. If the value provided for comparison is ``None``, it will be
  2199. interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more details).
  2200. Examples::
  2201. Entry.objects.get(id__exact=14)
  2202. Entry.objects.get(id__exact=None)
  2203. SQL equivalents:
  2204. .. code-block:: sql
  2205. SELECT ... WHERE id = 14;
  2206. SELECT ... WHERE id IS NULL;
  2207. .. admonition:: MySQL comparisons
  2208. In MySQL, a database table's "collation" setting determines whether
  2209. ``exact`` comparisons are case-sensitive. This is a database setting, *not*
  2210. a Django setting. It's possible to configure your MySQL tables to use
  2211. case-sensitive comparisons, but some trade-offs are involved. For more
  2212. information about this, see the :ref:`collation section <mysql-collation>`
  2213. in the :doc:`databases </ref/databases>` documentation.
  2214. .. fieldlookup:: iexact
  2215. ``iexact``
  2216. ~~~~~~~~~~
  2217. Case-insensitive exact match. If the value provided for comparison is ``None``,
  2218. it will be interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more
  2219. details).
  2220. Example::
  2221. Blog.objects.get(name__iexact='beatles blog')
  2222. Blog.objects.get(name__iexact=None)
  2223. SQL equivalents:
  2224. .. code-block:: sql
  2225. SELECT ... WHERE name ILIKE 'beatles blog';
  2226. SELECT ... WHERE name IS NULL;
  2227. Note the first query will match ``'Beatles Blog'``, ``'beatles blog'``,
  2228. ``'BeAtLes BLoG'``, etc.
  2229. .. admonition:: SQLite users
  2230. When using the SQLite backend and non-ASCII strings, bear in mind the
  2231. :ref:`database note <sqlite-string-matching>` about string comparisons.
  2232. SQLite does not do case-insensitive matching for non-ASCII strings.
  2233. .. fieldlookup:: contains
  2234. ``contains``
  2235. ~~~~~~~~~~~~
  2236. Case-sensitive containment test.
  2237. Example::
  2238. Entry.objects.get(headline__contains='Lennon')
  2239. SQL equivalent:
  2240. .. code-block:: sql
  2241. SELECT ... WHERE headline LIKE '%Lennon%';
  2242. Note this will match the headline ``'Lennon honored today'`` but not ``'lennon
  2243. honored today'``.
  2244. .. admonition:: SQLite users
  2245. SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains``
  2246. acts like ``icontains`` for SQLite. See the :ref:`database note
  2247. <sqlite-string-matching>` for more information.
  2248. .. fieldlookup:: icontains
  2249. ``icontains``
  2250. ~~~~~~~~~~~~~
  2251. Case-insensitive containment test.
  2252. Example::
  2253. Entry.objects.get(headline__icontains='Lennon')
  2254. SQL equivalent:
  2255. .. code-block:: sql
  2256. SELECT ... WHERE headline ILIKE '%Lennon%';
  2257. .. admonition:: SQLite users
  2258. When using the SQLite backend and non-ASCII strings, bear in mind the
  2259. :ref:`database note <sqlite-string-matching>` about string comparisons.
  2260. .. fieldlookup:: in
  2261. ``in``
  2262. ~~~~~~
  2263. In a given iterable; often a list, tuple, or queryset. It's not a common use
  2264. case, but strings (being iterables) are accepted.
  2265. Examples::
  2266. Entry.objects.filter(id__in=[1, 3, 4])
  2267. Entry.objects.filter(headline__in='abc')
  2268. SQL equivalents:
  2269. .. code-block:: sql
  2270. SELECT ... WHERE id IN (1, 3, 4);
  2271. SELECT ... WHERE headline IN ('a', 'b', 'c');
  2272. You can also use a queryset to dynamically evaluate the list of values
  2273. instead of providing a list of literal values::
  2274. inner_qs = Blog.objects.filter(name__contains='Cheddar')
  2275. entries = Entry.objects.filter(blog__in=inner_qs)
  2276. This queryset will be evaluated as subselect statement:
  2277. .. code-block:: sql
  2278. SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')
  2279. If you pass in a ``QuerySet`` resulting from ``values()`` or ``values_list()``
  2280. as the value to an ``__in`` lookup, you need to ensure you are only extracting
  2281. one field in the result. For example, this will work (filtering on the blog
  2282. names)::
  2283. inner_qs = Blog.objects.filter(name__contains='Ch').values('name')
  2284. entries = Entry.objects.filter(blog__name__in=inner_qs)
  2285. This example will raise an exception, since the inner query is trying to
  2286. extract two field values, where only one is expected::
  2287. # Bad code! Will raise a TypeError.
  2288. inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id')
  2289. entries = Entry.objects.filter(blog__name__in=inner_qs)
  2290. .. _nested-queries-performance:
  2291. .. admonition:: Performance considerations
  2292. Be cautious about using nested queries and understand your database
  2293. server's performance characteristics (if in doubt, benchmark!). Some
  2294. database backends, most notably MySQL, don't optimize nested queries very
  2295. well. It is more efficient, in those cases, to extract a list of values
  2296. and then pass that into the second query. That is, execute two queries
  2297. instead of one::
  2298. values = Blog.objects.filter(
  2299. name__contains='Cheddar').values_list('pk', flat=True)
  2300. entries = Entry.objects.filter(blog__in=list(values))
  2301. Note the ``list()`` call around the Blog ``QuerySet`` to force execution of
  2302. the first query. Without it, a nested query would be executed, because
  2303. :ref:`querysets-are-lazy`.
  2304. .. fieldlookup:: gt
  2305. ``gt``
  2306. ~~~~~~
  2307. Greater than.
  2308. Example::
  2309. Entry.objects.filter(id__gt=4)
  2310. SQL equivalent:
  2311. .. code-block:: sql
  2312. SELECT ... WHERE id > 4;
  2313. .. fieldlookup:: gte
  2314. ``gte``
  2315. ~~~~~~~
  2316. Greater than or equal to.
  2317. .. fieldlookup:: lt
  2318. ``lt``
  2319. ~~~~~~
  2320. Less than.
  2321. .. fieldlookup:: lte
  2322. ``lte``
  2323. ~~~~~~~
  2324. Less than or equal to.
  2325. .. fieldlookup:: startswith
  2326. ``startswith``
  2327. ~~~~~~~~~~~~~~
  2328. Case-sensitive starts-with.
  2329. Example::
  2330. Entry.objects.filter(headline__startswith='Lennon')
  2331. SQL equivalent:
  2332. .. code-block:: sql
  2333. SELECT ... WHERE headline LIKE 'Lennon%';
  2334. SQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts
  2335. like ``istartswith`` for SQLite.
  2336. .. fieldlookup:: istartswith
  2337. ``istartswith``
  2338. ~~~~~~~~~~~~~~~
  2339. Case-insensitive starts-with.
  2340. Example::
  2341. Entry.objects.filter(headline__istartswith='Lennon')
  2342. SQL equivalent:
  2343. .. code-block:: sql
  2344. SELECT ... WHERE headline ILIKE 'Lennon%';
  2345. .. admonition:: SQLite users
  2346. When using the SQLite backend and non-ASCII strings, bear in mind the
  2347. :ref:`database note <sqlite-string-matching>` about string comparisons.
  2348. .. fieldlookup:: endswith
  2349. ``endswith``
  2350. ~~~~~~~~~~~~
  2351. Case-sensitive ends-with.
  2352. Example::
  2353. Entry.objects.filter(headline__endswith='Lennon')
  2354. SQL equivalent:
  2355. .. code-block:: sql
  2356. SELECT ... WHERE headline LIKE '%Lennon';
  2357. .. admonition:: SQLite users
  2358. SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith``
  2359. acts like ``iendswith`` for SQLite. Refer to the :ref:`database note
  2360. <sqlite-string-matching>` documentation for more.
  2361. .. fieldlookup:: iendswith
  2362. ``iendswith``
  2363. ~~~~~~~~~~~~~
  2364. Case-insensitive ends-with.
  2365. Example::
  2366. Entry.objects.filter(headline__iendswith='Lennon')
  2367. SQL equivalent:
  2368. .. code-block:: sql
  2369. SELECT ... WHERE headline ILIKE '%Lennon'
  2370. .. admonition:: SQLite users
  2371. When using the SQLite backend and non-ASCII strings, bear in mind the
  2372. :ref:`database note <sqlite-string-matching>` about string comparisons.
  2373. .. fieldlookup:: range
  2374. ``range``
  2375. ~~~~~~~~~
  2376. Range test (inclusive).
  2377. Example::
  2378. import datetime
  2379. start_date = datetime.date(2005, 1, 1)
  2380. end_date = datetime.date(2005, 3, 31)
  2381. Entry.objects.filter(pub_date__range=(start_date, end_date))
  2382. SQL equivalent:
  2383. .. code-block:: sql
  2384. SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
  2385. You can use ``range`` anywhere you can use ``BETWEEN`` in SQL — for dates,
  2386. numbers and even characters.
  2387. .. warning::
  2388. Filtering a ``DateTimeField`` with dates won't include items on the last
  2389. day, because the bounds are interpreted as "0am on the given date". If
  2390. ``pub_date`` was a ``DateTimeField``, the above expression would be turned
  2391. into this SQL:
  2392. .. code-block:: sql
  2393. SELECT ... WHERE pub_date BETWEEN '2005-01-01 00:00:00' and '2005-03-31 00:00:00';
  2394. Generally speaking, you can't mix dates and datetimes.
  2395. .. fieldlookup:: date
  2396. ``date``
  2397. ~~~~~~~~
  2398. For datetime fields, casts the value as date. Allows chaining additional field
  2399. lookups. Takes a date value.
  2400. Example::
  2401. Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
  2402. Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
  2403. (No equivalent SQL code fragment is included for this lookup because
  2404. implementation of the relevant query varies among different database engines.)
  2405. When :setting:`USE_TZ` is ``True``, fields are converted to the current time
  2406. zone before filtering. This requires :ref:`time zone definitions in the
  2407. database <database-time-zone-definitions>`.
  2408. .. fieldlookup:: year
  2409. ``year``
  2410. ~~~~~~~~
  2411. For date and datetime fields, an exact year match. Allows chaining additional
  2412. field lookups. Takes an integer year.
  2413. Example::
  2414. Entry.objects.filter(pub_date__year=2005)
  2415. Entry.objects.filter(pub_date__year__gte=2005)
  2416. SQL equivalent:
  2417. .. code-block:: sql
  2418. SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31';
  2419. SELECT ... WHERE pub_date >= '2005-01-01';
  2420. (The exact SQL syntax varies for each database engine.)
  2421. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2422. current time zone before filtering. This requires :ref:`time zone definitions
  2423. in the database <database-time-zone-definitions>`.
  2424. .. fieldlookup:: iso_year
  2425. ``iso_year``
  2426. ~~~~~~~~~~~~
  2427. For date and datetime fields, an exact ISO 8601 week-numbering year match.
  2428. Allows chaining additional field lookups. Takes an integer year.
  2429. Example::
  2430. Entry.objects.filter(pub_date__iso_year=2005)
  2431. Entry.objects.filter(pub_date__iso_year__gte=2005)
  2432. (The exact SQL syntax varies for each database engine.)
  2433. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2434. current time zone before filtering. This requires :ref:`time zone definitions
  2435. in the database <database-time-zone-definitions>`.
  2436. .. fieldlookup:: month
  2437. ``month``
  2438. ~~~~~~~~~
  2439. For date and datetime fields, an exact month match. Allows chaining additional
  2440. field lookups. Takes an integer 1 (January) through 12 (December).
  2441. Example::
  2442. Entry.objects.filter(pub_date__month=12)
  2443. Entry.objects.filter(pub_date__month__gte=6)
  2444. SQL equivalent:
  2445. .. code-block:: sql
  2446. SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
  2447. SELECT ... WHERE EXTRACT('month' FROM pub_date) >= '6';
  2448. (The exact SQL syntax varies for each database engine.)
  2449. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2450. current time zone before filtering. This requires :ref:`time zone definitions
  2451. in the database <database-time-zone-definitions>`.
  2452. .. fieldlookup:: day
  2453. ``day``
  2454. ~~~~~~~
  2455. For date and datetime fields, an exact day match. Allows chaining additional
  2456. field lookups. Takes an integer day.
  2457. Example::
  2458. Entry.objects.filter(pub_date__day=3)
  2459. Entry.objects.filter(pub_date__day__gte=3)
  2460. SQL equivalent:
  2461. .. code-block:: sql
  2462. SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
  2463. SELECT ... WHERE EXTRACT('day' FROM pub_date) >= '3';
  2464. (The exact SQL syntax varies for each database engine.)
  2465. Note this will match any record with a pub_date on the third day of the month,
  2466. such as January 3, July 3, etc.
  2467. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2468. current time zone before filtering. This requires :ref:`time zone definitions
  2469. in the database <database-time-zone-definitions>`.
  2470. .. fieldlookup:: week
  2471. ``week``
  2472. ~~~~~~~~
  2473. For date and datetime fields, return the week number (1-52 or 53) according
  2474. to `ISO-8601 <https://en.wikipedia.org/wiki/ISO-8601>`_, i.e., weeks start
  2475. on a Monday and the first week contains the year's first Thursday.
  2476. Example::
  2477. Entry.objects.filter(pub_date__week=52)
  2478. Entry.objects.filter(pub_date__week__gte=32, pub_date__week__lte=38)
  2479. (No equivalent SQL code fragment is included for this lookup because
  2480. implementation of the relevant query varies among different database engines.)
  2481. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2482. current time zone before filtering. This requires :ref:`time zone definitions
  2483. in the database <database-time-zone-definitions>`.
  2484. .. fieldlookup:: week_day
  2485. ``week_day``
  2486. ~~~~~~~~~~~~
  2487. For date and datetime fields, a 'day of the week' match. Allows chaining
  2488. additional field lookups.
  2489. Takes an integer value representing the day of week from 1 (Sunday) to 7
  2490. (Saturday).
  2491. Example::
  2492. Entry.objects.filter(pub_date__week_day=2)
  2493. Entry.objects.filter(pub_date__week_day__gte=2)
  2494. (No equivalent SQL code fragment is included for this lookup because
  2495. implementation of the relevant query varies among different database engines.)
  2496. Note this will match any record with a ``pub_date`` that falls on a Monday (day
  2497. 2 of the week), regardless of the month or year in which it occurs. Week days
  2498. are indexed with day 1 being Sunday and day 7 being Saturday.
  2499. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2500. current time zone before filtering. This requires :ref:`time zone definitions
  2501. in the database <database-time-zone-definitions>`.
  2502. .. fieldlookup:: iso_week_day
  2503. ``iso_week_day``
  2504. ~~~~~~~~~~~~~~~~
  2505. For date and datetime fields, an exact ISO 8601 day of the week match. Allows
  2506. chaining additional field lookups.
  2507. Takes an integer value representing the day of the week from 1 (Monday) to 7
  2508. (Sunday).
  2509. Example::
  2510. Entry.objects.filter(pub_date__iso_week_day=1)
  2511. Entry.objects.filter(pub_date__iso_week_day__gte=1)
  2512. (No equivalent SQL code fragment is included for this lookup because
  2513. implementation of the relevant query varies among different database engines.)
  2514. Note this will match any record with a ``pub_date`` that falls on a Monday (day
  2515. 1 of the week), regardless of the month or year in which it occurs. Week days
  2516. are indexed with day 1 being Monday and day 7 being Sunday.
  2517. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2518. current time zone before filtering. This requires :ref:`time zone definitions
  2519. in the database <database-time-zone-definitions>`.
  2520. .. fieldlookup:: quarter
  2521. ``quarter``
  2522. ~~~~~~~~~~~
  2523. For date and datetime fields, a 'quarter of the year' match. Allows chaining
  2524. additional field lookups. Takes an integer value between 1 and 4 representing
  2525. the quarter of the year.
  2526. Example to retrieve entries in the second quarter (April 1 to June 30)::
  2527. Entry.objects.filter(pub_date__quarter=2)
  2528. (No equivalent SQL code fragment is included for this lookup because
  2529. implementation of the relevant query varies among different database engines.)
  2530. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2531. current time zone before filtering. This requires :ref:`time zone definitions
  2532. in the database <database-time-zone-definitions>`.
  2533. .. fieldlookup:: time
  2534. ``time``
  2535. ~~~~~~~~
  2536. For datetime fields, casts the value as time. Allows chaining additional field
  2537. lookups. Takes a :class:`datetime.time` value.
  2538. Example::
  2539. Entry.objects.filter(pub_date__time=datetime.time(14, 30))
  2540. Entry.objects.filter(pub_date__time__range=(datetime.time(8), datetime.time(17)))
  2541. (No equivalent SQL code fragment is included for this lookup because
  2542. implementation of the relevant query varies among different database engines.)
  2543. When :setting:`USE_TZ` is ``True``, fields are converted to the current time
  2544. zone before filtering. This requires :ref:`time zone definitions in the
  2545. database <database-time-zone-definitions>`.
  2546. .. fieldlookup:: hour
  2547. ``hour``
  2548. ~~~~~~~~
  2549. For datetime and time fields, an exact hour match. Allows chaining additional
  2550. field lookups. Takes an integer between 0 and 23.
  2551. Example::
  2552. Event.objects.filter(timestamp__hour=23)
  2553. Event.objects.filter(time__hour=5)
  2554. Event.objects.filter(timestamp__hour__gte=12)
  2555. SQL equivalent:
  2556. .. code-block:: sql
  2557. SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';
  2558. SELECT ... WHERE EXTRACT('hour' FROM time) = '5';
  2559. SELECT ... WHERE EXTRACT('hour' FROM timestamp) >= '12';
  2560. (The exact SQL syntax varies for each database engine.)
  2561. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2562. current time zone before filtering. This requires :ref:`time zone definitions
  2563. in the database <database-time-zone-definitions>`.
  2564. .. fieldlookup:: minute
  2565. ``minute``
  2566. ~~~~~~~~~~
  2567. For datetime and time fields, an exact minute match. Allows chaining additional
  2568. field lookups. Takes an integer between 0 and 59.
  2569. Example::
  2570. Event.objects.filter(timestamp__minute=29)
  2571. Event.objects.filter(time__minute=46)
  2572. Event.objects.filter(timestamp__minute__gte=29)
  2573. SQL equivalent:
  2574. .. code-block:: sql
  2575. SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';
  2576. SELECT ... WHERE EXTRACT('minute' FROM time) = '46';
  2577. SELECT ... WHERE EXTRACT('minute' FROM timestamp) >= '29';
  2578. (The exact SQL syntax varies for each database engine.)
  2579. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2580. current time zone before filtering. This requires :ref:`time zone definitions
  2581. in the database <database-time-zone-definitions>`.
  2582. .. fieldlookup:: second
  2583. ``second``
  2584. ~~~~~~~~~~
  2585. For datetime and time fields, an exact second match. Allows chaining additional
  2586. field lookups. Takes an integer between 0 and 59.
  2587. Example::
  2588. Event.objects.filter(timestamp__second=31)
  2589. Event.objects.filter(time__second=2)
  2590. Event.objects.filter(timestamp__second__gte=31)
  2591. SQL equivalent:
  2592. .. code-block:: sql
  2593. SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';
  2594. SELECT ... WHERE EXTRACT('second' FROM time) = '2';
  2595. SELECT ... WHERE EXTRACT('second' FROM timestamp) >= '31';
  2596. (The exact SQL syntax varies for each database engine.)
  2597. When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
  2598. current time zone before filtering. This requires :ref:`time zone definitions
  2599. in the database <database-time-zone-definitions>`.
  2600. .. fieldlookup:: isnull
  2601. ``isnull``
  2602. ~~~~~~~~~~
  2603. Takes either ``True`` or ``False``, which correspond to SQL queries of
  2604. ``IS NULL`` and ``IS NOT NULL``, respectively.
  2605. Example::
  2606. Entry.objects.filter(pub_date__isnull=True)
  2607. SQL equivalent:
  2608. .. code-block:: sql
  2609. SELECT ... WHERE pub_date IS NULL;
  2610. .. fieldlookup:: regex
  2611. ``regex``
  2612. ~~~~~~~~~
  2613. Case-sensitive regular expression match.
  2614. The regular expression syntax is that of the database backend in use.
  2615. In the case of SQLite, which has no built in regular expression support,
  2616. this feature is provided by a (Python) user-defined REGEXP function, and
  2617. the regular expression syntax is therefore that of Python's ``re`` module.
  2618. Example::
  2619. Entry.objects.get(title__regex=r'^(An?|The) +')
  2620. SQL equivalents:
  2621. .. code-block:: sql
  2622. SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL
  2623. SELECT ... WHERE REGEXP_LIKE(title, '^(An?|The) +', 'c'); -- Oracle
  2624. SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL
  2625. SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite
  2626. Using raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the
  2627. regular expression syntax is recommended.
  2628. .. fieldlookup:: iregex
  2629. ``iregex``
  2630. ~~~~~~~~~~
  2631. Case-insensitive regular expression match.
  2632. Example::
  2633. Entry.objects.get(title__iregex=r'^(an?|the) +')
  2634. SQL equivalents:
  2635. .. code-block:: sql
  2636. SELECT ... WHERE title REGEXP '^(an?|the) +'; -- MySQL
  2637. SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'i'); -- Oracle
  2638. SELECT ... WHERE title ~* '^(an?|the) +'; -- PostgreSQL
  2639. SELECT ... WHERE title REGEXP '(?i)^(an?|the) +'; -- SQLite
  2640. .. _aggregation-functions:
  2641. Aggregation functions
  2642. ---------------------
  2643. .. currentmodule:: django.db.models
  2644. Django provides the following aggregation functions in the
  2645. ``django.db.models`` module. For details on how to use these
  2646. aggregate functions, see :doc:`the topic guide on aggregation
  2647. </topics/db/aggregation>`. See the :class:`~django.db.models.Aggregate`
  2648. documentation to learn how to create your aggregates.
  2649. .. warning::
  2650. SQLite can't handle aggregation on date/time fields out of the box.
  2651. This is because there are no native date/time fields in SQLite and Django
  2652. currently emulates these features using a text field. Attempts to use
  2653. aggregation on date/time fields in SQLite will raise ``NotSupportedError``.
  2654. .. admonition:: Note
  2655. Aggregation functions return ``None`` when used with an empty
  2656. ``QuerySet``. For example, the ``Sum`` aggregation function returns ``None``
  2657. instead of ``0`` if the ``QuerySet`` contains no entries. To return another
  2658. value instead, pass a value to the ``default`` argument. An exception is
  2659. ``Count``, which does return ``0`` if the ``QuerySet`` is empty. ``Count``
  2660. does not support the ``default`` argument.
  2661. All aggregates have the following parameters in common:
  2662. ``expressions``
  2663. ~~~~~~~~~~~~~~~
  2664. Strings that reference fields on the model, transforms of the field, or
  2665. :doc:`query expressions </ref/models/expressions>`.
  2666. ``output_field``
  2667. ~~~~~~~~~~~~~~~~
  2668. An optional argument that represents the :doc:`model field </ref/models/fields>`
  2669. of the return value
  2670. .. note::
  2671. When combining multiple field types, Django can only determine the
  2672. ``output_field`` if all fields are of the same type. Otherwise, you
  2673. must provide the ``output_field`` yourself.
  2674. .. _aggregate-filter:
  2675. ``filter``
  2676. ~~~~~~~~~~
  2677. An optional :class:`Q object <django.db.models.Q>` that's used to filter the
  2678. rows that are aggregated.
  2679. See :ref:`conditional-aggregation` and :ref:`filtering-on-annotations` for
  2680. example usage.
  2681. .. _aggregate-default:
  2682. ``default``
  2683. ~~~~~~~~~~~
  2684. An optional argument that allows specifying a value to use as a default value
  2685. when the queryset (or grouping) contains no entries.
  2686. ``**extra``
  2687. ~~~~~~~~~~~
  2688. Keyword arguments that can provide extra context for the SQL generated
  2689. by the aggregate.
  2690. ``Avg``
  2691. ~~~~~~~
  2692. .. class:: Avg(expression, output_field=None, distinct=False, filter=None, default=None, **extra)
  2693. Returns the mean value of the given expression, which must be numeric
  2694. unless you specify a different ``output_field``.
  2695. * Default alias: ``<field>__avg``
  2696. * Return type: ``float`` if input is ``int``, otherwise same as input
  2697. field, or ``output_field`` if supplied
  2698. .. attribute:: distinct
  2699. Optional. If ``distinct=True``, ``Avg`` returns the mean value of
  2700. unique values. This is the SQL equivalent of ``AVG(DISTINCT <field>)``.
  2701. The default value is ``False``.
  2702. ``Count``
  2703. ~~~~~~~~~
  2704. .. class:: Count(expression, distinct=False, filter=None, **extra)
  2705. Returns the number of objects that are related through the provided
  2706. expression.
  2707. * Default alias: ``<field>__count``
  2708. * Return type: ``int``
  2709. .. attribute:: distinct
  2710. Optional. If ``distinct=True``, the count will only include unique
  2711. instances. This is the SQL equivalent of ``COUNT(DISTINCT <field>)``.
  2712. The default value is ``False``.
  2713. .. note::
  2714. The ``default`` argument is not supported.
  2715. ``Max``
  2716. ~~~~~~~
  2717. .. class:: Max(expression, output_field=None, filter=None, default=None, **extra)
  2718. Returns the maximum value of the given expression.
  2719. * Default alias: ``<field>__max``
  2720. * Return type: same as input field, or ``output_field`` if supplied
  2721. ``Min``
  2722. ~~~~~~~
  2723. .. class:: Min(expression, output_field=None, filter=None, default=None, **extra)
  2724. Returns the minimum value of the given expression.
  2725. * Default alias: ``<field>__min``
  2726. * Return type: same as input field, or ``output_field`` if supplied
  2727. ``StdDev``
  2728. ~~~~~~~~~~
  2729. .. class:: StdDev(expression, output_field=None, sample=False, filter=None, default=None, **extra)
  2730. Returns the standard deviation of the data in the provided expression.
  2731. * Default alias: ``<field>__stddev``
  2732. * Return type: ``float`` if input is ``int``, otherwise same as input
  2733. field, or ``output_field`` if supplied
  2734. .. attribute:: sample
  2735. Optional. By default, ``StdDev`` returns the population standard
  2736. deviation. However, if ``sample=True``, the return value will be the
  2737. sample standard deviation.
  2738. ``Sum``
  2739. ~~~~~~~
  2740. .. class:: Sum(expression, output_field=None, distinct=False, filter=None, default=None, **extra)
  2741. Computes the sum of all values of the given expression.
  2742. * Default alias: ``<field>__sum``
  2743. * Return type: same as input field, or ``output_field`` if supplied
  2744. .. attribute:: distinct
  2745. Optional. If ``distinct=True``, ``Sum`` returns the sum of unique
  2746. values. This is the SQL equivalent of ``SUM(DISTINCT <field>)``. The
  2747. default value is ``False``.
  2748. ``Variance``
  2749. ~~~~~~~~~~~~
  2750. .. class:: Variance(expression, output_field=None, sample=False, filter=None, default=None, **extra)
  2751. Returns the variance of the data in the provided expression.
  2752. * Default alias: ``<field>__variance``
  2753. * Return type: ``float`` if input is ``int``, otherwise same as input
  2754. field, or ``output_field`` if supplied
  2755. .. attribute:: sample
  2756. Optional. By default, ``Variance`` returns the population variance.
  2757. However, if ``sample=True``, the return value will be the sample
  2758. variance.
  2759. Query-related tools
  2760. ===================
  2761. This section provides reference material for query-related tools not documented
  2762. elsewhere.
  2763. ``Q()`` objects
  2764. ---------------
  2765. .. class:: Q
  2766. A ``Q()`` object represents an SQL condition that can be used in
  2767. database-related operations. It's similar to how an
  2768. :class:`F() <django.db.models.F>` object represents the value of a model field
  2769. or annotation. They make it possible to define and reuse conditions, and
  2770. combine them using operators such as ``|`` (``OR``), ``&`` (``AND``), and ``^``
  2771. (``XOR``). See :ref:`complex-lookups-with-q`.
  2772. .. versionchanged:: 4.1
  2773. Support for the ``^`` (``XOR``) operator was added.
  2774. ``Prefetch()`` objects
  2775. ----------------------
  2776. .. class:: Prefetch(lookup, queryset=None, to_attr=None)
  2777. The ``Prefetch()`` object can be used to control the operation of
  2778. :meth:`~django.db.models.query.QuerySet.prefetch_related()`.
  2779. The ``lookup`` argument describes the relations to follow and works the same
  2780. as the string based lookups passed to
  2781. :meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example:
  2782. >>> from django.db.models import Prefetch
  2783. >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all()
  2784. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
  2785. # This will only execute two queries regardless of the number of Question
  2786. # and Choice objects.
  2787. >>> Question.objects.prefetch_related(Prefetch('choice_set'))
  2788. <QuerySet [<Question: What's up?>]>
  2789. The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup.
  2790. This is useful to further filter down the prefetch operation, or to call
  2791. :meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched
  2792. relation, hence reducing the number of queries even further:
  2793. >>> voted_choices = Choice.objects.filter(votes__gt=0)
  2794. >>> voted_choices
  2795. <QuerySet [<Choice: The sky>]>
  2796. >>> prefetch = Prefetch('choice_set', queryset=voted_choices)
  2797. >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()
  2798. <QuerySet [<Choice: The sky>]>
  2799. The ``to_attr`` argument sets the result of the prefetch operation to a custom
  2800. attribute:
  2801. >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')
  2802. >>> Question.objects.prefetch_related(prefetch).get().voted_choices
  2803. [<Choice: The sky>]
  2804. >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()
  2805. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
  2806. .. note::
  2807. When using ``to_attr`` the prefetched result is stored in a list. This can
  2808. provide a significant speed improvement over traditional
  2809. ``prefetch_related`` calls which store the cached result within a
  2810. ``QuerySet`` instance.
  2811. ``prefetch_related_objects()``
  2812. ------------------------------
  2813. .. function:: prefetch_related_objects(model_instances, *related_lookups)
  2814. Prefetches the given lookups on an iterable of model instances. This is useful
  2815. in code that receives a list of model instances as opposed to a ``QuerySet``;
  2816. for example, when fetching models from a cache or instantiating them manually.
  2817. Pass an iterable of model instances (must all be of the same class) and the
  2818. lookups or :class:`Prefetch` objects you want to prefetch for. For example::
  2819. >>> from django.db.models import prefetch_related_objects
  2820. >>> restaurants = fetch_top_restaurants_from_cache() # A list of Restaurants
  2821. >>> prefetch_related_objects(restaurants, 'pizzas__toppings')
  2822. When using multiple databases with ``prefetch_related_objects``, the prefetch
  2823. query will use the database associated with the model instance. This can be
  2824. overridden by using a custom queryset in a related lookup.
  2825. ``FilteredRelation()`` objects
  2826. ------------------------------
  2827. .. class:: FilteredRelation(relation_name, *, condition=Q())
  2828. .. attribute:: FilteredRelation.relation_name
  2829. The name of the field on which you'd like to filter the relation.
  2830. .. attribute:: FilteredRelation.condition
  2831. A :class:`~django.db.models.Q` object to control the filtering.
  2832. ``FilteredRelation`` is used with :meth:`~.QuerySet.annotate()` to create an
  2833. ``ON`` clause when a ``JOIN`` is performed. It doesn't act on the default
  2834. relationship but on the annotation name (``pizzas_vegetarian`` in example
  2835. below).
  2836. For example, to find restaurants that have vegetarian pizzas with
  2837. ``'mozzarella'`` in the name::
  2838. >>> from django.db.models import FilteredRelation, Q
  2839. >>> Restaurant.objects.annotate(
  2840. ... pizzas_vegetarian=FilteredRelation(
  2841. ... 'pizzas', condition=Q(pizzas__vegetarian=True),
  2842. ... ),
  2843. ... ).filter(pizzas_vegetarian__name__icontains='mozzarella')
  2844. If there are a large number of pizzas, this queryset performs better than::
  2845. >>> Restaurant.objects.filter(
  2846. ... pizzas__vegetarian=True,
  2847. ... pizzas__name__icontains='mozzarella',
  2848. ... )
  2849. because the filtering in the ``WHERE`` clause of the first queryset will only
  2850. operate on vegetarian pizzas.
  2851. ``FilteredRelation`` doesn't support:
  2852. * :meth:`.QuerySet.only` and :meth:`~.QuerySet.prefetch_related`.
  2853. * A :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
  2854. inherited from a parent model.