querysets.txt 83 KB

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