querysets.txt 142 KB

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