querysets.txt 100 KB

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