querysets.txt 151 KB

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