querysets.txt 61 KB

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