querysets.txt 146 KB

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