querysets.txt 131 KB

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