querysets.txt 69 KB

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