querysets.txt 80 KB

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