querysets.txt 58 KB

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