querysets.txt 130 KB

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