querysets.txt 51 KB

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