querysets.txt 149 KB

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