querysets.txt 112 KB

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