querysets.txt 88 KB

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