querysets.txt 134 KB

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