querysets.txt 89 KB

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