querysets.txt 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. ======================
  2. QuerySet API reference
  3. ======================
  4. .. currentmodule:: django.db.models.QuerySet
  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. * **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
  25. be sliced, using Python's array-slicing syntax. Usually slicing a
  26. ``QuerySet`` returns another (unevaluated) ``QuerySet``, but Django will
  27. execute the database query if you use the "step" parameter of slice
  28. syntax.
  29. * **Pickling/Caching.** See the following section for details of what
  30. is involved when `pickling QuerySets`_. The important thing for the
  31. purposes of this section is that the results are read from the database.
  32. * **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
  33. This is for convenience in the Python interactive interpreter, so you can
  34. immediately see your results when using the API interactively.
  35. * **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
  36. This, as you might expect, returns the length of the result list.
  37. Note: *Don't* use ``len()`` on ``QuerySet``\s if all you want to do is
  38. determine the number of records in the set. It's much more efficient to
  39. handle a count at the database level, using SQL's ``SELECT COUNT(*)``,
  40. and Django provides a ``count()`` method for precisely this reason. See
  41. ``count()`` below.
  42. * **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
  43. it. For example::
  44. entry_list = list(Entry.objects.all())
  45. Be warned, though, that this could have a large memory overhead, because
  46. Django will load each element of the list into memory. In contrast,
  47. iterating over a ``QuerySet`` will take advantage of your database to
  48. load data and instantiate objects only as you need them.
  49. * **bool().** Testing a ``QuerySet`` in a boolean context, such as using
  50. ``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query
  51. to be executed. If there is at least one result, the ``QuerySet`` is
  52. ``True``, otherwise ``False``. For example::
  53. if Entry.objects.filter(headline="Test"):
  54. print "There is at least one Entry with the headline Test"
  55. Note: *Don't* use this if all you want to do is determine if at least one
  56. result exists, and don't need the actual objects. It's more efficient to
  57. use ``exists()`` (see below).
  58. .. _pickling QuerySets:
  59. Pickling QuerySets
  60. ------------------
  61. If you pickle_ a ``QuerySet``, this will force all the results to be loaded
  62. into memory prior to pickling. Pickling is usually used as a precursor to
  63. caching and when the cached queryset is reloaded, you want the results to
  64. already be present and ready for use (reading from the database can take some
  65. time, defeating the purpose of caching). This means that when you unpickle a
  66. ``QuerySet``, it contains the results at the moment it was pickled, rather
  67. than the results that are currently in the database.
  68. If you only want to pickle the necessary information to recreate the
  69. ``QuerySet`` from the database at a later time, pickle the ``query`` attribute
  70. of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
  71. any results loaded) using some code like this::
  72. >>> import pickle
  73. >>> query = pickle.loads(s) # Assuming 's' is the pickled string.
  74. >>> qs = MyModel.objects.all()
  75. >>> qs.query = query # Restore the original 'query'.
  76. The ``query`` attribute is an opaque object. It represents the internals of
  77. the query construction and is not part of the public API. However, it is safe
  78. (and fully supported) to pickle and unpickle the attribute's contents as
  79. described here.
  80. .. admonition:: You can't share pickles between versions
  81. Pickles of QuerySets are only valid for the version of Django that
  82. was used to generate them. If you generate a pickle using Django
  83. version N, there is no guarantee that pickle will be readable with
  84. Django version N+1. Pickles should not be used as part of a long-term
  85. archival strategy.
  86. .. _pickle: http://docs.python.org/library/pickle.html
  87. .. _queryset-api:
  88. QuerySet API
  89. ============
  90. Though you usually won't create one manually -- you'll go through a
  91. :class:`Manager` -- here's the formal declaration of a ``QuerySet``:
  92. .. class:: QuerySet([model=None])
  93. Usually when you'll interact with a ``QuerySet`` you'll use it by :ref:`chaining
  94. filters <chaining-filters>`. To make this work, most ``QuerySet`` methods return new querysets.
  95. Methods that return new QuerySets
  96. ---------------------------------
  97. Django provides a range of ``QuerySet`` refinement methods that modify either
  98. the types of results returned by the ``QuerySet`` or the way its SQL query is
  99. executed.
  100. filter
  101. ~~~~~~
  102. .. method:: filter(**kwargs)
  103. Returns a new ``QuerySet`` containing objects that match the given lookup
  104. parameters.
  105. The lookup parameters (``**kwargs``) should be in the format described in
  106. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
  107. underlying SQL statement.
  108. exclude
  109. ~~~~~~~
  110. .. method:: exclude(**kwargs)
  111. Returns a new ``QuerySet`` containing objects that do *not* match the given
  112. lookup parameters.
  113. The lookup parameters (``**kwargs``) should be in the format described in
  114. `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
  115. underlying SQL statement, and the whole thing is enclosed in a ``NOT()``.
  116. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
  117. AND whose ``headline`` is "Hello"::
  118. Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
  119. In SQL terms, that evaluates to::
  120. SELECT ...
  121. WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
  122. This example excludes all entries whose ``pub_date`` is later than 2005-1-3
  123. OR whose headline is "Hello"::
  124. Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
  125. In SQL terms, that evaluates to::
  126. SELECT ...
  127. WHERE NOT pub_date > '2005-1-3'
  128. AND NOT headline = 'Hello'
  129. Note the second example is more restrictive.
  130. annotate
  131. ~~~~~~~~
  132. .. method:: annotate(*args, **kwargs)
  133. Annotates each object in the ``QuerySet`` with the provided list of
  134. aggregate values (averages, sums, etc) that have been computed over
  135. the objects that are related to the objects in the ``QuerySet``.
  136. Each argument to ``annotate()`` is an annotation that will be added
  137. to each object in the ``QuerySet`` that is returned.
  138. The aggregation functions that are provided by Django are described
  139. in `Aggregation Functions`_ below.
  140. Annotations specified using keyword arguments will use the keyword as
  141. the alias for the annotation. Anonymous arguments will have an alias
  142. generated for them based upon the name of the aggregate function and
  143. the model field that is being aggregated.
  144. For example, if you were manipulating a list of blogs, you may want
  145. to determine how many entries have been made in each blog::
  146. >>> q = Blog.objects.annotate(Count('entry'))
  147. # The name of the first blog
  148. >>> q[0].name
  149. 'Blogasaurus'
  150. # The number of entries on the first blog
  151. >>> q[0].entry__count
  152. 42
  153. The ``Blog`` model doesn't define an ``entry__count`` attribute by itself,
  154. but by using a keyword argument to specify the aggregate function, you can
  155. control the name of the annotation::
  156. >>> q = Blog.objects.annotate(number_of_entries=Count('entry'))
  157. # The number of entries on the first blog, using the name provided
  158. >>> q[0].number_of_entries
  159. 42
  160. For an in-depth discussion of aggregation, see :doc:`the topic guide on
  161. Aggregation </topics/db/aggregation>`.
  162. order_by
  163. ~~~~~~~~
  164. .. method:: order_by(*fields)
  165. By default, results returned by a ``QuerySet`` are ordered by the ordering
  166. tuple given by the ``ordering`` option in the model's ``Meta``. You can
  167. override this on a per-``QuerySet`` basis by using the ``order_by`` method.
  168. Example::
  169. Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
  170. The result above will be ordered by ``pub_date`` descending, then by
  171. ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
  172. *descending* order. Ascending order is implied. To order randomly, use ``"?"``,
  173. like so::
  174. Entry.objects.order_by('?')
  175. Note: ``order_by('?')`` queries may be expensive and slow, depending on the
  176. database backend you're using.
  177. To order by a field in a different model, use the same syntax as when you are
  178. querying across model relations. That is, the name of the field, followed by a
  179. double underscore (``__``), followed by the name of the field in the new model,
  180. and so on for as many models as you want to join. For example::
  181. Entry.objects.order_by('blog__name', 'headline')
  182. If you try to order by a field that is a relation to another model, Django will
  183. use the default ordering on the related model (or order by the related model's
  184. primary key if there is no ``Meta.ordering`` specified. For example::
  185. Entry.objects.order_by('blog')
  186. ...is identical to::
  187. Entry.objects.order_by('blog__id')
  188. ...since the ``Blog`` model has no default ordering specified.
  189. Be cautious when ordering by fields in related models if you are also using
  190. ``distinct()``. See the note in :meth:`distinct` for an explanation of how
  191. related model ordering can change the expected results.
  192. It is permissible to specify a multi-valued field to order the results by (for
  193. example, a ``ManyToMany`` field). Normally this won't be a sensible thing to
  194. do and it's really an advanced usage feature. However, if you know that your
  195. queryset's filtering or available data implies that there will only be one
  196. ordering piece of data for each of the main items you are selecting, the
  197. ordering may well be exactly what you want to do. Use ordering on multi-valued
  198. fields with care and make sure the results are what you expect.
  199. There's no way to specify whether ordering should be case sensitive. With
  200. respect to case-sensitivity, Django will order results however your database
  201. backend normally orders them.
  202. If you don't want any ordering to be applied to a query, not even the default
  203. ordering, call ``order_by()`` with no parameters.
  204. You can tell if a query is ordered or not by checking the
  205. :attr:`QuerySet.ordered` attribute, which will be ``True`` if the
  206. ``QuerySet`` has been ordered in any way.
  207. reverse
  208. ~~~~~~~
  209. .. method:: reverse()
  210. Use the ``reverse()`` method to reverse the order in which a queryset's
  211. elements are returned. Calling ``reverse()`` a second time restores the
  212. ordering back to the normal direction.
  213. To retrieve the ''last'' five items in a queryset, you could do this::
  214. my_queryset.reverse()[:5]
  215. Note that this is not quite the same as slicing from the end of a sequence in
  216. Python. The above example will return the last item first, then the
  217. penultimate item and so on. If we had a Python sequence and looked at
  218. ``seq[-5:]``, we would see the fifth-last item first. Django doesn't support
  219. that mode of access (slicing from the end), because it's not possible to do it
  220. efficiently in SQL.
  221. Also, note that ``reverse()`` should generally only be called on a
  222. ``QuerySet`` which has a defined ordering (e.g., when querying against
  223. a model which defines a default ordering, or when using
  224. ``order_by()``). If no such ordering is defined for a given
  225. ``QuerySet``, calling ``reverse()`` on it has no real effect (the
  226. ordering was undefined prior to calling ``reverse()``, and will remain
  227. undefined afterward).
  228. distinct
  229. ~~~~~~~~
  230. .. method:: distinct()
  231. Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
  232. eliminates duplicate rows from the query results.
  233. By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
  234. is rarely a problem, because simple queries such as ``Blog.objects.all()``
  235. don't introduce the possibility of duplicate result rows. However, if your
  236. query spans multiple tables, it's possible to get duplicate results when a
  237. ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
  238. .. note::
  239. Any fields used in an :meth:`order_by` call are included in the SQL
  240. ``SELECT`` columns. This can sometimes lead to unexpected results when
  241. used in conjunction with ``distinct()``. If you order by fields from a
  242. related model, those fields will be added to the selected columns and they
  243. may make otherwise duplicate rows appear to be distinct. Since the extra
  244. columns don't appear in the returned results (they are only there to
  245. support ordering), it sometimes looks like non-distinct results are being
  246. returned.
  247. Similarly, if you use a ``values()`` query to restrict the columns
  248. selected, the columns used in any ``order_by()`` (or default model
  249. ordering) will still be involved and may affect uniqueness of the results.
  250. The moral here is that if you are using ``distinct()`` be careful about
  251. ordering by related models. Similarly, when using ``distinct()`` and
  252. ``values()`` together, be careful when ordering by fields not in the
  253. ``values()`` call.
  254. values
  255. ~~~~~~
  256. .. method:: values(*fields)
  257. Returns a ``ValuesQuerySet`` -- a ``QuerySet`` that returns dictionaries when
  258. used as an iterable, rather than model-instance objects.
  259. Each of those dictionaries represents an object, with the keys corresponding to
  260. the attribute names of model objects.
  261. This example compares the dictionaries of ``values()`` with the normal model
  262. objects::
  263. # This list contains a Blog object.
  264. >>> Blog.objects.filter(name__startswith='Beatles')
  265. [<Blog: Beatles Blog>]
  266. # This list contains a dictionary.
  267. >>> Blog.objects.filter(name__startswith='Beatles').values()
  268. [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
  269. ``values()`` takes optional positional arguments, ``*fields``, which specify
  270. field names to which the ``SELECT`` should be limited. If you specify the
  271. fields, each dictionary will contain only the field keys/values for the fields
  272. you specify. If you don't specify the fields, each dictionary will contain a
  273. key and value for every field in the database table.
  274. Example::
  275. >>> Blog.objects.values()
  276. [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
  277. >>> Blog.objects.values('id', 'name')
  278. [{'id': 1, 'name': 'Beatles Blog'}]
  279. A few subtleties that are worth mentioning:
  280. * If you have a field called ``foo`` that is a
  281. :class:`~django.db.models.ForeignKey`, the default ``values()`` call
  282. will return a dictionary key called ``foo_id``, since this is the name
  283. of the hidden model attribute that stores the actual value (the ``foo``
  284. attribute refers to the related model). When you are calling
  285. ``values()`` and passing in field names, you can pass in either ``foo``
  286. or ``foo_id`` and you will get back the same thing (the dictionary key
  287. will match the field name you passed in).
  288. For example::
  289. >>> Entry.objects.values()
  290. [{'blog_id': 1, 'headline': u'First Entry', ...}, ...]
  291. >>> Entry.objects.values('blog')
  292. [{'blog': 1}, ...]
  293. >>> Entry.objects.values('blog_id')
  294. [{'blog_id': 1}, ...]
  295. * When using ``values()`` together with ``distinct()``, be aware that
  296. ordering can affect the results. See the note in :meth:`distinct` for
  297. details.
  298. * If you use a ``values()`` clause after an ``extra()`` clause,
  299. any fields defined by a ``select`` argument in the ``extra()``
  300. must be explicitly included in the ``values()`` clause. However,
  301. if the ``extra()`` clause is used after the ``values()``, the
  302. fields added by the select will be included automatically.
  303. A ``ValuesQuerySet`` is useful when you know you're only going to need values
  304. from a small number of the available fields and you won't need the
  305. functionality of a model instance object. It's more efficient to select only
  306. the fields you need to use.
  307. Finally, note a ``ValuesQuerySet`` is a subclass of ``QuerySet``, so it has all
  308. methods of ``QuerySet``. You can call ``filter()`` on it, or ``order_by()``, or
  309. whatever. Yes, that means these two calls are identical::
  310. Blog.objects.values().order_by('id')
  311. Blog.objects.order_by('id').values()
  312. The people who made Django prefer to put all the SQL-affecting methods first,
  313. followed (optionally) by any output-affecting methods (such as ``values()``),
  314. but it doesn't really matter. This is your chance to really flaunt your
  315. individualism.
  316. .. versionchanged:: 1.3
  317. The ``values()`` method previously did not return anything for
  318. :class:`~django.db.models.ManyToManyField` attributes and would raise an error
  319. if you tried to pass this type of field to it.
  320. This restriction has been lifted, and you can now also refer to fields on
  321. related models with reverse relations through ``OneToOneField``, ``ForeignKey``
  322. and ``ManyToManyField`` attributes::
  323. Blog.objects.values('name', 'entry__headline')
  324. [{'name': 'My blog', 'entry__headline': 'An entry'},
  325. {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]
  326. .. warning::
  327. Because :class:`~django.db.models.ManyToManyField` attributes and reverse
  328. relations can have multiple related rows, including these can have a
  329. multiplier effect on the size of your result set. This will be especially
  330. pronounced if you include multiple such fields in your ``values()`` query,
  331. in which case all possible combinations will be returned.
  332. values_list
  333. ~~~~~~~~~~~
  334. .. method:: values_list(*fields)
  335. This is similar to ``values()`` except that instead of returning dictionaries,
  336. it returns tuples when iterated over. Each tuple contains the value from the
  337. respective field passed into the ``values_list()`` call -- so the first item is
  338. the first field, etc. For example::
  339. >>> Entry.objects.values_list('id', 'headline')
  340. [(1, u'First entry'), ...]
  341. If you only pass in a single field, you can also pass in the ``flat``
  342. parameter. If ``True``, this will mean the returned results are single values,
  343. rather than one-tuples. An example should make the difference clearer::
  344. >>> Entry.objects.values_list('id').order_by('id')
  345. [(1,), (2,), (3,), ...]
  346. >>> Entry.objects.values_list('id', flat=True).order_by('id')
  347. [1, 2, 3, ...]
  348. It is an error to pass in ``flat`` when there is more than one field.
  349. If you don't pass any values to ``values_list()``, it will return all the
  350. fields in the model, in the order they were declared.
  351. dates
  352. ~~~~~
  353. .. method:: dates(field, kind, order='ASC')
  354. Returns a ``DateQuerySet`` -- a ``QuerySet`` that evaluates to a list of
  355. ``datetime.datetime`` objects representing all available dates of a particular
  356. kind within the contents of the ``QuerySet``.
  357. ``field`` should be the name of a ``DateField`` or ``DateTimeField`` of your
  358. model.
  359. ``kind`` should be either ``"year"``, ``"month"`` or ``"day"``. Each
  360. ``datetime.datetime`` object in the result list is "truncated" to the given
  361. ``type``.
  362. * ``"year"`` returns a list of all distinct year values for the field.
  363. * ``"month"`` returns a list of all distinct year/month values for the field.
  364. * ``"day"`` returns a list of all distinct year/month/day values for the field.
  365. ``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
  366. ``'DESC'``. This specifies how to order the results.
  367. Examples::
  368. >>> Entry.objects.dates('pub_date', 'year')
  369. [datetime.datetime(2005, 1, 1)]
  370. >>> Entry.objects.dates('pub_date', 'month')
  371. [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
  372. >>> Entry.objects.dates('pub_date', 'day')
  373. [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
  374. >>> Entry.objects.dates('pub_date', 'day', order='DESC')
  375. [datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]
  376. >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
  377. [datetime.datetime(2005, 3, 20)]
  378. none
  379. ~~~~
  380. .. method:: none()
  381. Returns an ``EmptyQuerySet`` -- a ``QuerySet`` that always evaluates to
  382. an empty list. This can be used in cases where you know that you should
  383. return an empty result set and your caller is expecting a ``QuerySet``
  384. object (instead of returning an empty list, for example.)
  385. Examples::
  386. >>> Entry.objects.none()
  387. []
  388. all
  389. ~~~
  390. .. method:: all()
  391. Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass you
  392. pass in). This can be useful in some situations where you might want to pass
  393. in either a model manager or a ``QuerySet`` and do further filtering on the
  394. result. You can safely call ``all()`` on either object and then you'll
  395. definitely have a ``QuerySet`` to work with.
  396. .. _select-related:
  397. select_related
  398. ~~~~~~~~~~~~~~
  399. .. method:: select_related()
  400. Returns a ``QuerySet`` that will automatically "follow" foreign-key
  401. relationships, selecting that additional related-object data when it executes
  402. its query. This is a performance booster which results in (sometimes much)
  403. larger queries but means later use of foreign-key relationships won't require
  404. database queries.
  405. The following examples illustrate the difference between plain lookups and
  406. ``select_related()`` lookups. Here's standard lookup::
  407. # Hits the database.
  408. e = Entry.objects.get(id=5)
  409. # Hits the database again to get the related Blog object.
  410. b = e.blog
  411. And here's ``select_related`` lookup::
  412. # Hits the database.
  413. e = Entry.objects.select_related().get(id=5)
  414. # Doesn't hit the database, because e.blog has been prepopulated
  415. # in the previous query.
  416. b = e.blog
  417. ``select_related()`` follows foreign keys as far as possible. If you have the
  418. following models::
  419. class City(models.Model):
  420. # ...
  421. class Person(models.Model):
  422. # ...
  423. hometown = models.ForeignKey(City)
  424. class Book(models.Model):
  425. # ...
  426. author = models.ForeignKey(Person)
  427. ...then a call to ``Book.objects.select_related().get(id=4)`` will cache the
  428. related ``Person`` *and* the related ``City``::
  429. b = Book.objects.select_related().get(id=4)
  430. p = b.author # Doesn't hit the database.
  431. c = p.hometown # Doesn't hit the database.
  432. b = Book.objects.get(id=4) # No select_related() in this example.
  433. p = b.author # Hits the database.
  434. c = p.hometown # Hits the database.
  435. Note that, by default, ``select_related()`` does not follow foreign keys that
  436. have ``null=True``.
  437. Usually, using ``select_related()`` can vastly improve performance because your
  438. app can avoid many database calls. However, in situations with deeply nested
  439. sets of relationships ``select_related()`` can sometimes end up following "too
  440. many" relations, and can generate queries so large that they end up being slow.
  441. In these situations, you can use the ``depth`` argument to ``select_related()``
  442. to control how many "levels" of relations ``select_related()`` will actually
  443. follow::
  444. b = Book.objects.select_related(depth=1).get(id=4)
  445. p = b.author # Doesn't hit the database.
  446. c = p.hometown # Requires a database call.
  447. Sometimes you only want to access specific models that are related to your root
  448. model, not all of the related models. In these cases, you can pass the related
  449. field names to ``select_related()`` and it will only follow those relations.
  450. You can even do this for models that are more than one relation away by
  451. separating the field names with double underscores, just as for filters. For
  452. example, if you have this model::
  453. class Room(models.Model):
  454. # ...
  455. building = models.ForeignKey(...)
  456. class Group(models.Model):
  457. # ...
  458. teacher = models.ForeignKey(...)
  459. room = models.ForeignKey(Room)
  460. subject = models.ForeignKey(...)
  461. ...and you only needed to work with the ``room`` and ``subject`` attributes,
  462. you could write this::
  463. g = Group.objects.select_related('room', 'subject')
  464. This is also valid::
  465. g = Group.objects.select_related('room__building', 'subject')
  466. ...and would also pull in the ``building`` relation.
  467. You can refer to any ``ForeignKey`` or ``OneToOneField`` relation in
  468. the list of fields passed to ``select_related``. Ths includes foreign
  469. keys that have ``null=True`` (unlike the default ``select_related()``
  470. call). It's an error to use both a list of fields and the ``depth``
  471. parameter in the same ``select_related()`` call, since they are
  472. conflicting options.
  473. .. versionchanged:: 1.2
  474. You can also refer to the reverse direction of a ``OneToOneFields`` in
  475. the list of fields passed to ``select_related`` -- that is, you can traverse
  476. a ``OneToOneField`` back to the object on which the field is defined. Instead
  477. of specifying the field name, use the ``related_name`` for the field on the
  478. related object.
  479. ``OneToOneFields`` will not be traversed in the reverse direction if you
  480. are performing a depth-based ``select_related``.
  481. extra
  482. ~~~~~
  483. .. method:: extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
  484. Sometimes, the Django query syntax by itself can't easily express a complex
  485. ``WHERE`` clause. For these edge cases, Django provides the ``extra()``
  486. ``QuerySet`` modifier -- a hook for injecting specific clauses into the SQL
  487. generated by a ``QuerySet``.
  488. By definition, these extra lookups may not be portable to different database
  489. engines (because you're explicitly writing SQL code) and violate the DRY
  490. principle, so you should avoid them if possible.
  491. Specify one or more of ``params``, ``select``, ``where`` or ``tables``. None
  492. of the arguments is required, but you should use at least one of them.
  493. * ``select``
  494. The ``select`` argument lets you put extra fields in the ``SELECT`` clause.
  495. It should be a dictionary mapping attribute names to SQL clauses to use to
  496. calculate that attribute.
  497. Example::
  498. Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
  499. As a result, each ``Entry`` object will have an extra attribute,
  500. ``is_recent``, a boolean representing whether the entry's ``pub_date`` is
  501. greater than Jan. 1, 2006.
  502. Django inserts the given SQL snippet directly into the ``SELECT``
  503. statement, so the resulting SQL of the above example would be something
  504. like::
  505. SELECT blog_entry.*, (pub_date > '2006-01-01') AS is_recent
  506. FROM blog_entry;
  507. The next example is more advanced; it does a subquery to give each
  508. resulting ``Blog`` object an ``entry_count`` attribute, an integer count
  509. of associated ``Entry`` objects::
  510. Blog.objects.extra(
  511. select={
  512. 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
  513. },
  514. )
  515. (In this particular case, we're exploiting the fact that the query will
  516. already contain the ``blog_blog`` table in its ``FROM`` clause.)
  517. The resulting SQL of the above example would be::
  518. SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id) AS entry_count
  519. FROM blog_blog;
  520. Note that the parenthesis required by most database engines around
  521. subqueries are not required in Django's ``select`` clauses. Also note that
  522. some database backends, such as some MySQL versions, don't support
  523. subqueries.
  524. In some rare cases, you might wish to pass parameters to the SQL fragments
  525. in ``extra(select=...)``. For this purpose, use the ``select_params``
  526. parameter. Since ``select_params`` is a sequence and the ``select``
  527. attribute is a dictionary, some care is required so that the parameters
  528. are matched up correctly with the extra select pieces. In this situation,
  529. you should use a ``django.utils.datastructures.SortedDict`` for the
  530. ``select`` value, not just a normal Python dictionary.
  531. This will work, for example::
  532. Blog.objects.extra(
  533. select=SortedDict([('a', '%s'), ('b', '%s')]),
  534. select_params=('one', 'two'))
  535. The only thing to be careful about when using select parameters in
  536. ``extra()`` is to avoid using the substring ``"%%s"`` (that's *two*
  537. percent characters before the ``s``) in the select strings. Django's
  538. tracking of parameters looks for ``%s`` and an escaped ``%`` character
  539. like this isn't detected. That will lead to incorrect results.
  540. * ``where`` / ``tables``
  541. You can define explicit SQL ``WHERE`` clauses -- perhaps to perform
  542. non-explicit joins -- by using ``where``. You can manually add tables to
  543. the SQL ``FROM`` clause by using ``tables``.
  544. ``where`` and ``tables`` both take a list of strings. All ``where``
  545. parameters are "AND"ed to any other search criteria.
  546. Example::
  547. Entry.objects.extra(where=['id IN (3, 4, 5, 20)'])
  548. ...translates (roughly) into the following SQL::
  549. SELECT * FROM blog_entry WHERE id IN (3, 4, 5, 20);
  550. Be careful when using the ``tables`` parameter if you're specifying
  551. tables that are already used in the query. When you add extra tables
  552. via the ``tables`` parameter, Django assumes you want that table included
  553. an extra time, if it is already included. That creates a problem,
  554. since the table name will then be given an alias. If a table appears
  555. multiple times in an SQL statement, the second and subsequent occurrences
  556. must use aliases so the database can tell them apart. If you're
  557. referring to the extra table you added in the extra ``where`` parameter
  558. this is going to cause errors.
  559. Normally you'll only be adding extra tables that don't already appear in
  560. the query. However, if the case outlined above does occur, there are a few
  561. solutions. First, see if you can get by without including the extra table
  562. and use the one already in the query. If that isn't possible, put your
  563. ``extra()`` call at the front of the queryset construction so that your
  564. table is the first use of that table. Finally, if all else fails, look at
  565. the query produced and rewrite your ``where`` addition to use the alias
  566. given to your extra table. The alias will be the same each time you
  567. construct the queryset in the same way, so you can rely upon the alias
  568. name to not change.
  569. * ``order_by``
  570. If you need to order the resulting queryset using some of the new fields
  571. or tables you have included via ``extra()`` use the ``order_by`` parameter
  572. to ``extra()`` and pass in a sequence of strings. These strings should
  573. either be model fields (as in the normal ``order_by()`` method on
  574. querysets), of the form ``table_name.column_name`` or an alias for a column
  575. that you specified in the ``select`` parameter to ``extra()``.
  576. For example::
  577. q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
  578. q = q.extra(order_by = ['-is_recent'])
  579. This would sort all the items for which ``is_recent`` is true to the front
  580. of the result set (``True`` sorts before ``False`` in a descending
  581. ordering).
  582. This shows, by the way, that you can make multiple calls to
  583. ``extra()`` and it will behave as you expect (adding new constraints each
  584. time).
  585. * ``params``
  586. The ``where`` parameter described above may use standard Python database
  587. string placeholders -- ``'%s'`` to indicate parameters the database engine
  588. should automatically quote. The ``params`` argument is a list of any extra
  589. parameters to be substituted.
  590. Example::
  591. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
  592. Always use ``params`` instead of embedding values directly into ``where``
  593. because ``params`` will ensure values are quoted correctly according to
  594. your particular backend. (For example, quotes will be escaped correctly.)
  595. Bad::
  596. Entry.objects.extra(where=["headline='Lennon'"])
  597. Good::
  598. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
  599. defer
  600. ~~~~~
  601. .. method:: defer(*fields)
  602. In some complex data-modeling situations, your models might contain a lot of
  603. fields, some of which could contain a lot of data (for example, text fields),
  604. or require expensive processing to convert them to Python objects. If you are
  605. using the results of a queryset in some situation where you know you don't
  606. need those particular fields, you can tell Django not to retrieve them from
  607. the database.
  608. This is done by passing the names of the fields to not load to ``defer()``::
  609. Entry.objects.defer("headline", "body")
  610. A queryset that has deferred fields will still return model instances. Each
  611. deferred field will be retrieved from the database if you access that field
  612. (one at a time, not all the deferred fields at once).
  613. You can make multiple calls to ``defer()``. Each call adds new fields to the
  614. deferred set::
  615. # Defers both the body and headline fields.
  616. Entry.objects.defer("body").filter(rating=5).defer("headline")
  617. The order in which fields are added to the deferred set does not matter.
  618. Calling ``defer()`` with a field name that has already been deferred is
  619. harmless (the field will still be deferred).
  620. You can defer loading of fields in related models (if the related models are
  621. loading via ``select_related()``) by using the standard double-underscore
  622. notation to separate related fields::
  623. Blog.objects.select_related().defer("entry__headline", "entry__body")
  624. If you want to clear the set of deferred fields, pass ``None`` as a parameter
  625. to ``defer()``::
  626. # Load all fields immediately.
  627. my_queryset.defer(None)
  628. Some fields in a model won't be deferred, even if you ask for them. You can
  629. never defer the loading of the primary key. If you are using
  630. ``select_related()`` to retrieve other models at the same time you shouldn't
  631. defer the loading of the field that connects from the primary model to the
  632. related one (at the moment, that doesn't raise an error, but it will
  633. eventually).
  634. .. note::
  635. The ``defer()`` method (and its cousin, ``only()``, below) are only for
  636. advanced use-cases. They provide an optimization for when you have
  637. analyzed your queries closely and understand *exactly* what information
  638. you need and have measured that the difference between returning the
  639. fields you need and the full set of fields for the model will be
  640. significant. When you are initially developing your applications, don't
  641. bother using ``defer()``; leave it until your query construction has
  642. settled down and you understand where the hot-points are.
  643. only
  644. ~~~~
  645. .. method:: only(*fields)
  646. The ``only()`` method is more or less the opposite of ``defer()``. You
  647. call it with the fields that should *not* be deferred when retrieving a model.
  648. If you have a model where almost all the fields need to be deferred, using
  649. ``only()`` to specify the complementary set of fields could result in simpler
  650. code.
  651. If you have a model with fields ``name``, ``age`` and ``biography``, the
  652. following two querysets are the same, in terms of deferred fields::
  653. Person.objects.defer("age", "biography")
  654. Person.objects.only("name")
  655. Whenever you call ``only()`` it *replaces* the set of fields to load
  656. immediately. The method's name is mnemonic: **only** those fields are loaded
  657. immediately; the remainder are deferred. Thus, successive calls to ``only()``
  658. result in only the final fields being considered::
  659. # This will defer all fields except the headline.
  660. Entry.objects.only("body", "rating").only("headline")
  661. Since ``defer()`` acts incrementally (adding fields to the deferred list), you
  662. can combine calls to ``only()`` and ``defer()`` and things will behave
  663. logically::
  664. # Final result is that everything except "headline" is deferred.
  665. Entry.objects.only("headline", "body").defer("body")
  666. # Final result loads headline and body immediately (only() replaces any
  667. # existing set of fields).
  668. Entry.objects.defer("body").only("headline", "body")
  669. using
  670. ~~~~~
  671. .. method:: using(alias)
  672. .. versionadded:: 1.2
  673. This method is for controlling which database the ``QuerySet`` will be
  674. evaluated against if you are using more than one database. The only argument
  675. this method takes is the alias of a database, as defined in
  676. :setting:`DATABASES`.
  677. For example::
  678. # queries the database with the 'default' alias.
  679. >>> Entry.objects.all()
  680. # queries the database with the 'backup' alias
  681. >>> Entry.objects.using('backup')
  682. Methods that do not return QuerySets
  683. ------------------------------------
  684. The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
  685. something *other than* a ``QuerySet``.
  686. These methods do not use a cache (see :ref:`caching-and-querysets`). Rather,
  687. they query the database each time they're called.
  688. get
  689. ~~~
  690. .. method:: get(**kwargs)
  691. Returns the object matching the given lookup parameters, which should be in
  692. the format described in `Field lookups`_.
  693. ``get()`` raises ``MultipleObjectsReturned`` if more than one object was
  694. found. The ``MultipleObjectsReturned`` exception is an attribute of the model
  695. class.
  696. ``get()`` raises a ``DoesNotExist`` exception if an object wasn't found for
  697. the given parameters. This exception is also an attribute of the model class.
  698. Example::
  699. Entry.objects.get(id='foo') # raises Entry.DoesNotExist
  700. The ``DoesNotExist`` exception inherits from
  701. ``django.core.exceptions.ObjectDoesNotExist``, so you can target multiple
  702. ``DoesNotExist`` exceptions. Example::
  703. from django.core.exceptions import ObjectDoesNotExist
  704. try:
  705. e = Entry.objects.get(id=3)
  706. b = Blog.objects.get(id=1)
  707. except ObjectDoesNotExist:
  708. print "Either the entry or blog doesn't exist."
  709. create
  710. ~~~~~~
  711. .. method:: create(**kwargs)
  712. A convenience method for creating an object and saving it all in one step. Thus::
  713. p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
  714. and::
  715. p = Person(first_name="Bruce", last_name="Springsteen")
  716. p.save(force_insert=True)
  717. are equivalent.
  718. The :ref:`force_insert <ref-models-force-insert>` parameter is documented
  719. elsewhere, but all it means is that a new object will always be created.
  720. Normally you won't need to worry about this. However, if your model contains a
  721. manual primary key value that you set and if that value already exists in the
  722. database, a call to ``create()`` will fail with an :exc:`IntegrityError` since
  723. primary keys must be unique. So remember to be prepared to handle the exception
  724. if you are using manual primary keys.
  725. get_or_create
  726. ~~~~~~~~~~~~~
  727. .. method:: get_or_create(**kwargs)
  728. A convenience method for looking up an object with the given kwargs, creating
  729. one if necessary.
  730. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
  731. created object and ``created`` is a boolean specifying whether a new object was
  732. created.
  733. This is meant as a shortcut to boilerplatish code and is mostly useful for
  734. data-import scripts. For example::
  735. try:
  736. obj = Person.objects.get(first_name='John', last_name='Lennon')
  737. except Person.DoesNotExist:
  738. obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
  739. obj.save()
  740. This pattern gets quite unwieldy as the number of fields in a model goes up.
  741. The above example can be rewritten using ``get_or_create()`` like so::
  742. obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
  743. defaults={'birthday': date(1940, 10, 9)})
  744. Any keyword arguments passed to ``get_or_create()`` -- *except* an optional one
  745. called ``defaults`` -- will be used in a ``get()`` call. If an object is found,
  746. ``get_or_create()`` returns a tuple of that object and ``False``. If an object
  747. is *not* found, ``get_or_create()`` will instantiate and save a new object,
  748. returning a tuple of the new object and ``True``. The new object will be
  749. created roughly according to this algorithm::
  750. defaults = kwargs.pop('defaults', {})
  751. params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
  752. params.update(defaults)
  753. obj = self.model(**params)
  754. obj.save()
  755. In English, that means start with any non-``'defaults'`` keyword argument that
  756. doesn't contain a double underscore (which would indicate a non-exact lookup).
  757. Then add the contents of ``defaults``, overriding any keys if necessary, and
  758. use the result as the keyword arguments to the model class. As hinted at
  759. above, this is a simplification of the algorithm that is used, but it contains
  760. all the pertinent details. The internal implementation has some more
  761. error-checking than this and handles some extra edge-conditions; if you're
  762. interested, read the code.
  763. If you have a field named ``defaults`` and want to use it as an exact lookup in
  764. ``get_or_create()``, just use ``'defaults__exact'``, like so::
  765. Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
  766. The ``get_or_create()`` method has similar error behaviour to ``create()``
  767. when you are using manually specified primary keys. If an object needs to be
  768. created and the key already exists in the database, an ``IntegrityError`` will
  769. be raised.
  770. Finally, a word on using ``get_or_create()`` in Django views. As mentioned
  771. earlier, ``get_or_create()`` is mostly useful in scripts that need to parse
  772. data and create new records if existing ones aren't available. But if you need
  773. to use ``get_or_create()`` in a view, please make sure to use it only in
  774. ``POST`` requests unless you have a good reason not to. ``GET`` requests
  775. shouldn't have any effect on data; use ``POST`` whenever a request to a page
  776. has a side effect on your data. For more, see `Safe methods`_ in the HTTP spec.
  777. .. _Safe methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
  778. count
  779. ~~~~~
  780. .. method:: count()
  781. Returns an integer representing the number of objects in the database matching
  782. the ``QuerySet``. ``count()`` never raises exceptions.
  783. Example::
  784. # Returns the total number of entries in the database.
  785. Entry.objects.count()
  786. # Returns the number of entries whose headline contains 'Lennon'
  787. Entry.objects.filter(headline__contains='Lennon').count()
  788. ``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should
  789. always use ``count()`` rather than loading all of the record into Python
  790. objects and calling ``len()`` on the result (unless you need to load the
  791. objects into memory anyway, in which case ``len()`` will be faster).
  792. Depending on which database you're using (e.g. PostgreSQL vs. MySQL),
  793. ``count()`` may return a long integer instead of a normal Python integer. This
  794. is an underlying implementation quirk that shouldn't pose any real-world
  795. problems.
  796. in_bulk
  797. ~~~~~~~
  798. .. method:: in_bulk(id_list)
  799. Takes a list of primary-key values and returns a dictionary mapping each
  800. primary-key value to an instance of the object with the given ID.
  801. Example::
  802. >>> Blog.objects.in_bulk([1])
  803. {1: <Blog: Beatles Blog>}
  804. >>> Blog.objects.in_bulk([1, 2])
  805. {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
  806. >>> Blog.objects.in_bulk([])
  807. {}
  808. If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.
  809. iterator
  810. ~~~~~~~~
  811. .. method:: iterator()
  812. Evaluates the ``QuerySet`` (by performing the query) and returns an
  813. `iterator`_ over the results. A ``QuerySet`` typically caches its
  814. results internally so that repeated evaluations do not result in
  815. additional queries; ``iterator()`` will instead read results directly,
  816. without doing any caching at the ``QuerySet`` level. For a
  817. ``QuerySet`` which returns a large number of objects, this often
  818. results in better performance and a significant reduction in memory
  819. Note that using ``iterator()`` on a ``QuerySet`` which has already
  820. been evaluated will force it to evaluate again, repeating the query.
  821. .. _iterator: http://www.python.org/dev/peps/pep-0234/
  822. latest
  823. ~~~~~~
  824. .. method:: latest(field_name=None)
  825. Returns the latest object in the table, by date, using the ``field_name``
  826. provided as the date field.
  827. This example returns the latest ``Entry`` in the table, according to the
  828. ``pub_date`` field::
  829. Entry.objects.latest('pub_date')
  830. If your model's ``Meta`` specifies ``get_latest_by``, you can leave off the
  831. ``field_name`` argument to ``latest()``. Django will use the field specified in
  832. ``get_latest_by`` by default.
  833. Like ``get()``, ``latest()`` raises ``DoesNotExist`` if an object doesn't
  834. exist with the given parameters.
  835. Note ``latest()`` exists purely for convenience and readability.
  836. aggregate
  837. ~~~~~~~~~
  838. .. method:: aggregate(*args, **kwargs)
  839. Returns a dictionary of aggregate values (averages, sums, etc) calculated
  840. over the ``QuerySet``. Each argument to ``aggregate()`` specifies
  841. a value that will be included in the dictionary that is returned.
  842. The aggregation functions that are provided by Django are described
  843. in `Aggregation Functions`_ below.
  844. Aggregates specified using keyword arguments will use the keyword as
  845. the name for the annotation. Anonymous arguments will have an name
  846. generated for them based upon the name of the aggregate function and
  847. the model field that is being aggregated.
  848. For example, if you were manipulating blog entries, you may want to know
  849. the number of authors that have contributed blog entries::
  850. >>> q = Blog.objects.aggregate(Count('entry'))
  851. {'entry__count': 16}
  852. By using a keyword argument to specify the aggregate function, you can
  853. control the name of the aggregation value that is returned::
  854. >>> q = Blog.objects.aggregate(number_of_entries=Count('entry'))
  855. {'number_of_entries': 16}
  856. For an in-depth discussion of aggregation, see :doc:`the topic guide on
  857. Aggregation </topics/db/aggregation>`.
  858. exists
  859. ~~~~~~
  860. .. method:: exists()
  861. .. versionadded:: 1.2
  862. Returns ``True`` if the :class:`QuerySet` contains any results, and ``False``
  863. if not. This tries to perform the query in the simplest and fastest way
  864. possible, but it *does* execute nearly the same query. This means that calling
  865. :meth:`QuerySet.exists()` is faster than ``bool(some_query_set)``, but not by
  866. a large degree. If ``some_query_set`` has not yet been evaluated, but you know
  867. that it will be at some point, then using ``some_query_set.exists()`` will do
  868. more overall work (an additional query) than simply using
  869. ``bool(some_query_set)``.
  870. update
  871. ~~~~~~
  872. .. method:: update(**kwargs)
  873. Performs an SQL update query for the specified fields, and returns
  874. the number of rows affected. The ``update()`` method is applied instantly and
  875. the only restriction on the :class:`QuerySet` that is updated is that it can
  876. only update columns in the model's main table. Filtering based on related
  877. fields is still possible. You cannot call ``update()`` on a
  878. :class:`QuerySet` that has had a slice taken or can otherwise no longer be
  879. filtered.
  880. For example, if you wanted to update all the entries in a particular blog
  881. to use the same headline::
  882. >>> b = Blog.objects.get(pk=1)
  883. # Update all the headlines belonging to this Blog.
  884. >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
  885. The ``update()`` method does a bulk update and does not call any ``save()``
  886. methods on your models, nor does it emit the ``pre_save`` or ``post_save``
  887. signals (which are a consequence of calling ``save()``).
  888. delete
  889. ~~~~~~
  890. .. method:: delete()
  891. Performs an SQL delete query on all rows in the :class:`QuerySet`. The
  892. ``delete()`` is applied instantly. You cannot call ``delete()`` on a
  893. :class:`QuerySet` that has had a slice taken or can otherwise no longer be
  894. filtered.
  895. For example, to delete all the entries in a particular blog::
  896. >>> b = Blog.objects.get(pk=1)
  897. # Delete all the entries belonging to this Blog.
  898. >>> Entry.objects.filter(blog=b).delete()
  899. By default, Django's :class:`~django.db.models.ForeignKey` emulates the SQL
  900. constraint ``ON DELETE CASCADE`` -- in other words, any objects with foreign
  901. keys pointing at the objects to be deleted will be deleted along with them.
  902. For example::
  903. blogs = Blog.objects.all()
  904. # This will delete all Blogs and all of their Entry objects.
  905. blogs.delete()
  906. .. versionadded:: 1.3
  907. This cascade behavior is customizable via the
  908. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  909. :class:`~django.db.models.ForeignKey`.
  910. The ``delete()`` method does a bulk delete and does not call any ``delete()``
  911. methods on your models. It does, however, emit the
  912. :data:`~django.db.models.signals.pre_delete` and
  913. :data:`~django.db.models.signals.post_delete` signals for all deleted objects
  914. (including cascaded deletions).
  915. .. _field-lookups:
  916. Field lookups
  917. -------------
  918. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
  919. specified as keyword arguments to the ``QuerySet`` methods ``filter()``,
  920. ``exclude()`` and ``get()``.
  921. For an introduction, see :ref:`field-lookups-intro`.
  922. .. fieldlookup:: exact
  923. exact
  924. ~~~~~
  925. Exact match. If the value provided for comparison is ``None``, it will
  926. be interpreted as an SQL ``NULL`` (See isnull_ for more details).
  927. Examples::
  928. Entry.objects.get(id__exact=14)
  929. Entry.objects.get(id__exact=None)
  930. SQL equivalents::
  931. SELECT ... WHERE id = 14;
  932. SELECT ... WHERE id IS NULL;
  933. .. admonition:: MySQL comparisons
  934. In MySQL, a database table's "collation" setting determines whether
  935. ``exact`` comparisons are case-sensitive. This is a database setting, *not*
  936. a Django setting. It's possible to configure your MySQL tables to use
  937. case-sensitive comparisons, but some trade-offs are involved. For more
  938. information about this, see the :ref:`collation section <mysql-collation>`
  939. in the :doc:`databases </ref/databases>` documentation.
  940. .. fieldlookup:: iexact
  941. iexact
  942. ~~~~~~
  943. Case-insensitive exact match.
  944. Example::
  945. Blog.objects.get(name__iexact='beatles blog')
  946. SQL equivalent::
  947. SELECT ... WHERE name ILIKE 'beatles blog';
  948. Note this will match ``'Beatles Blog'``, ``'beatles blog'``, ``'BeAtLes
  949. BLoG'``, etc.
  950. .. admonition:: SQLite users
  951. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  952. mind the :ref:`database note <sqlite-string-matching>` about string
  953. comparisons. SQLite does not do case-insensitive matching for Unicode
  954. strings.
  955. .. fieldlookup:: contains
  956. contains
  957. ~~~~~~~~
  958. Case-sensitive containment test.
  959. Example::
  960. Entry.objects.get(headline__contains='Lennon')
  961. SQL equivalent::
  962. SELECT ... WHERE headline LIKE '%Lennon%';
  963. Note this will match the headline ``'Today Lennon honored'`` but not
  964. ``'today lennon honored'``.
  965. SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains`` acts
  966. like ``icontains`` for SQLite.
  967. .. fieldlookup:: icontains
  968. icontains
  969. ~~~~~~~~~
  970. Case-insensitive containment test.
  971. Example::
  972. Entry.objects.get(headline__icontains='Lennon')
  973. SQL equivalent::
  974. SELECT ... WHERE headline ILIKE '%Lennon%';
  975. .. admonition:: SQLite users
  976. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  977. mind the :ref:`database note <sqlite-string-matching>` about string
  978. comparisons.
  979. .. fieldlookup:: in
  980. in
  981. ~~
  982. In a given list.
  983. Example::
  984. Entry.objects.filter(id__in=[1, 3, 4])
  985. SQL equivalent::
  986. SELECT ... WHERE id IN (1, 3, 4);
  987. You can also use a queryset to dynamically evaluate the list of values
  988. instead of providing a list of literal values::
  989. inner_qs = Blog.objects.filter(name__contains='Cheddar')
  990. entries = Entry.objects.filter(blog__in=inner_qs)
  991. This queryset will be evaluated as subselect statement::
  992. SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')
  993. The above code fragment could also be written as follows::
  994. inner_q = Blog.objects.filter(name__contains='Cheddar').values('pk').query
  995. entries = Entry.objects.filter(blog__in=inner_q)
  996. This second form is a bit less readable and unnatural to write, since it
  997. accesses the internal ``query`` attribute and requires a ``ValuesQuerySet``.
  998. If your code doesn't require compatibility with Django 1.0, use the first
  999. form, passing in a queryset directly.
  1000. If you pass in a ``ValuesQuerySet`` or ``ValuesListQuerySet`` (the result of
  1001. calling ``values()`` or ``values_list()`` on a queryset) as the value to an
  1002. ``__in`` lookup, you need to ensure you are only extracting one field in the
  1003. result. For example, this will work (filtering on the blog names)::
  1004. inner_qs = Blog.objects.filter(name__contains='Ch').values('name')
  1005. entries = Entry.objects.filter(blog__name__in=inner_qs)
  1006. This example will raise an exception, since the inner query is trying to
  1007. extract two field values, where only one is expected::
  1008. # Bad code! Will raise a TypeError.
  1009. inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id')
  1010. entries = Entry.objects.filter(blog__name__in=inner_qs)
  1011. .. warning::
  1012. This ``query`` attribute should be considered an opaque internal attribute.
  1013. It's fine to use it like above, but its API may change between Django
  1014. versions.
  1015. .. admonition:: Performance considerations
  1016. Be cautious about using nested queries and understand your database
  1017. server's performance characteristics (if in doubt, benchmark!). Some
  1018. database backends, most notably MySQL, don't optimize nested queries very
  1019. well. It is more efficient, in those cases, to extract a list of values
  1020. and then pass that into the second query. That is, execute two queries
  1021. instead of one::
  1022. values = Blog.objects.filter(
  1023. name__contains='Cheddar').values_list('pk', flat=True)
  1024. entries = Entry.objects.filter(blog__in=list(values))
  1025. Note the ``list()`` call around the Blog ``QuerySet`` to force execution of
  1026. the first query. Without it, a nested query would be executed, because
  1027. :ref:`querysets-are-lazy`.
  1028. .. fieldlookup:: gt
  1029. gt
  1030. ~~
  1031. Greater than.
  1032. Example::
  1033. Entry.objects.filter(id__gt=4)
  1034. SQL equivalent::
  1035. SELECT ... WHERE id > 4;
  1036. .. fieldlookup:: gte
  1037. gte
  1038. ~~~
  1039. Greater than or equal to.
  1040. .. fieldlookup:: lt
  1041. lt
  1042. ~~
  1043. Less than.
  1044. .. fieldlookup:: lte
  1045. lte
  1046. ~~~
  1047. Less than or equal to.
  1048. .. fieldlookup:: startswith
  1049. startswith
  1050. ~~~~~~~~~~
  1051. Case-sensitive starts-with.
  1052. Example::
  1053. Entry.objects.filter(headline__startswith='Will')
  1054. SQL equivalent::
  1055. SELECT ... WHERE headline LIKE 'Will%';
  1056. SQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts
  1057. like ``istartswith`` for SQLite.
  1058. .. fieldlookup:: istartswith
  1059. istartswith
  1060. ~~~~~~~~~~~
  1061. Case-insensitive starts-with.
  1062. Example::
  1063. Entry.objects.filter(headline__istartswith='will')
  1064. SQL equivalent::
  1065. SELECT ... WHERE headline ILIKE 'Will%';
  1066. .. admonition:: SQLite users
  1067. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  1068. mind the :ref:`database note <sqlite-string-matching>` about string
  1069. comparisons.
  1070. .. fieldlookup:: endswith
  1071. endswith
  1072. ~~~~~~~~
  1073. Case-sensitive ends-with.
  1074. Example::
  1075. Entry.objects.filter(headline__endswith='cats')
  1076. SQL equivalent::
  1077. SELECT ... WHERE headline LIKE '%cats';
  1078. SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith`` acts
  1079. like ``iendswith`` for SQLite.
  1080. .. fieldlookup:: iendswith
  1081. iendswith
  1082. ~~~~~~~~~
  1083. Case-insensitive ends-with.
  1084. Example::
  1085. Entry.objects.filter(headline__iendswith='will')
  1086. SQL equivalent::
  1087. SELECT ... WHERE headline ILIKE '%will'
  1088. .. admonition:: SQLite users
  1089. When using the SQLite backend and Unicode (non-ASCII) strings, bear in
  1090. mind the :ref:`database note <sqlite-string-matching>` about string
  1091. comparisons.
  1092. .. fieldlookup:: range
  1093. range
  1094. ~~~~~
  1095. Range test (inclusive).
  1096. Example::
  1097. start_date = datetime.date(2005, 1, 1)
  1098. end_date = datetime.date(2005, 3, 31)
  1099. Entry.objects.filter(pub_date__range=(start_date, end_date))
  1100. SQL equivalent::
  1101. SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
  1102. You can use ``range`` anywhere you can use ``BETWEEN`` in SQL -- for dates,
  1103. numbers and even characters.
  1104. .. fieldlookup:: year
  1105. year
  1106. ~~~~
  1107. For date/datetime fields, exact year match. Takes a four-digit year.
  1108. Example::
  1109. Entry.objects.filter(pub_date__year=2005)
  1110. SQL equivalent::
  1111. SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31 23:59:59.999999';
  1112. (The exact SQL syntax varies for each database engine.)
  1113. .. fieldlookup:: month
  1114. month
  1115. ~~~~~
  1116. For date/datetime fields, exact month match. Takes an integer 1 (January)
  1117. through 12 (December).
  1118. Example::
  1119. Entry.objects.filter(pub_date__month=12)
  1120. SQL equivalent::
  1121. SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
  1122. (The exact SQL syntax varies for each database engine.)
  1123. .. fieldlookup:: day
  1124. day
  1125. ~~~
  1126. For date/datetime fields, exact day match.
  1127. Example::
  1128. Entry.objects.filter(pub_date__day=3)
  1129. SQL equivalent::
  1130. SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
  1131. (The exact SQL syntax varies for each database engine.)
  1132. Note this will match any record with a pub_date on the third day of the month,
  1133. such as January 3, July 3, etc.
  1134. .. fieldlookup:: week_day
  1135. week_day
  1136. ~~~~~~~~
  1137. For date/datetime fields, a 'day of the week' match.
  1138. Takes an integer value representing the day of week from 1 (Sunday) to 7
  1139. (Saturday).
  1140. Example::
  1141. Entry.objects.filter(pub_date__week_day=2)
  1142. (No equivalent SQL code fragment is included for this lookup because
  1143. implementation of the relevant query varies among different database engines.)
  1144. Note this will match any record with a pub_date that falls on a Monday (day 2
  1145. of the week), regardless of the month or year in which it occurs. Week days
  1146. are indexed with day 1 being Sunday and day 7 being Saturday.
  1147. .. fieldlookup:: isnull
  1148. isnull
  1149. ~~~~~~
  1150. Takes either ``True`` or ``False``, which correspond to SQL queries of
  1151. ``IS NULL`` and ``IS NOT NULL``, respectively.
  1152. Example::
  1153. Entry.objects.filter(pub_date__isnull=True)
  1154. SQL equivalent::
  1155. SELECT ... WHERE pub_date IS NULL;
  1156. .. fieldlookup:: search
  1157. search
  1158. ~~~~~~
  1159. A boolean full-text search, taking advantage of full-text indexing. This is
  1160. like ``contains`` but is significantly faster due to full-text indexing.
  1161. Example::
  1162. Entry.objects.filter(headline__search="+Django -jazz Python")
  1163. SQL equivalent::
  1164. SELECT ... WHERE MATCH(tablename, headline) AGAINST (+Django -jazz Python IN BOOLEAN MODE);
  1165. Note this is only available in MySQL and requires direct manipulation of the
  1166. database to add the full-text index. By default Django uses BOOLEAN MODE for
  1167. full text searches. `See the MySQL documentation for additional details.
  1168. <http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html>`_
  1169. .. fieldlookup:: regex
  1170. regex
  1171. ~~~~~
  1172. Case-sensitive regular expression match.
  1173. The regular expression syntax is that of the database backend in use.
  1174. In the case of SQLite, which has no built in regular expression support,
  1175. this feature is provided by a (Python) user-defined REGEXP function, and
  1176. the regular expression syntax is therefore that of Python's ``re`` module.
  1177. Example::
  1178. Entry.objects.get(title__regex=r'^(An?|The) +')
  1179. SQL equivalents::
  1180. SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL
  1181. SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'c'); -- Oracle
  1182. SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL
  1183. SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite
  1184. Using raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the
  1185. regular expression syntax is recommended.
  1186. .. fieldlookup:: iregex
  1187. iregex
  1188. ~~~~~~
  1189. Case-insensitive regular expression match.
  1190. Example::
  1191. Entry.objects.get(title__iregex=r'^(an?|the) +')
  1192. SQL equivalents::
  1193. SELECT ... WHERE title REGEXP '^(an?|the) +'; -- MySQL
  1194. SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'i'); -- Oracle
  1195. SELECT ... WHERE title ~* '^(an?|the) +'; -- PostgreSQL
  1196. SELECT ... WHERE title REGEXP '(?i)^(an?|the) +'; -- SQLite
  1197. .. _aggregation-functions:
  1198. Aggregation functions
  1199. ---------------------
  1200. Django provides the following aggregation functions in the
  1201. ``django.db.models`` module. For details on how to use these
  1202. aggregate functions, see
  1203. :doc:`the topic guide on aggregation </topics/db/aggregation>`.
  1204. Avg
  1205. ~~~
  1206. .. class:: Avg(field)
  1207. Returns the mean value of the given field.
  1208. * Default alias: ``<field>__avg``
  1209. * Return type: float
  1210. Count
  1211. ~~~~~
  1212. .. class:: Count(field, distinct=False)
  1213. Returns the number of objects that are related through the provided field.
  1214. * Default alias: ``<field>__count``
  1215. * Return type: integer
  1216. Has one optional argument:
  1217. .. attribute:: distinct
  1218. If distinct=True, the count will only include unique instances. This has
  1219. the SQL equivalent of ``COUNT(DISTINCT field)``. Default value is ``False``.
  1220. Max
  1221. ~~~
  1222. .. class:: Max(field)
  1223. Returns the maximum value of the given field.
  1224. * Default alias: ``<field>__max``
  1225. * Return type: same as input field
  1226. Min
  1227. ~~~
  1228. .. class:: Min(field)
  1229. Returns the minimum value of the given field.
  1230. * Default alias: ``<field>__min``
  1231. * Return type: same as input field
  1232. StdDev
  1233. ~~~~~~
  1234. .. class:: StdDev(field, sample=False)
  1235. Returns the standard deviation of the data in the provided field.
  1236. * Default alias: ``<field>__stddev``
  1237. * Return type: float
  1238. Has one optional argument:
  1239. .. attribute:: sample
  1240. By default, ``StdDev`` returns the population standard deviation. However,
  1241. if ``sample=True``, the return value will be the sample standard deviation.
  1242. .. admonition:: SQLite
  1243. SQLite doesn't provide ``StdDev`` out of the box. An implementation is
  1244. available as an extension module for SQLite. Consult the SQlite
  1245. documentation for instructions on obtaining and installing this extension.
  1246. Sum
  1247. ~~~
  1248. .. class:: Sum(field)
  1249. Computes the sum of all values of the given field.
  1250. * Default alias: ``<field>__sum``
  1251. * Return type: same as input field
  1252. Variance
  1253. ~~~~~~~~
  1254. .. class:: Variance(field, sample=False)
  1255. Returns the variance of the data in the provided field.
  1256. * Default alias: ``<field>__variance``
  1257. * Return type: float
  1258. Has one optional argument:
  1259. .. attribute:: sample
  1260. By default, ``Variance`` returns the population variance. However,
  1261. if ``sample=True``, the return value will be the sample variance.
  1262. .. admonition:: SQLite
  1263. SQLite doesn't provide ``Variance`` out of the box. An implementation is
  1264. available as an extension module for SQLite. Consult the SQlite
  1265. documentation for instructions on obtaining and installing this extension.