querysets.txt 65 KB

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