querysets.txt 150 KB

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