querysets.txt 115 KB

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