2
0

querysets.txt 74 KB

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