querysets.txt 102 KB

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