querysets.txt 56 KB

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