querysets.txt 89 KB

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