querysets.txt 139 KB

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