queries.txt 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  1. ==============
  2. Making queries
  3. ==============
  4. .. currentmodule:: django.db.models
  5. Once you've created your :doc:`data models </topics/db/models>`, Django
  6. automatically gives you a database-abstraction API that lets you create,
  7. retrieve, update and delete objects. This document explains how to use this
  8. API. Refer to the :doc:`data model reference </ref/models/index>` for full
  9. details of all the various model lookup options.
  10. Throughout this guide (and in the reference), we'll refer to the following
  11. models, which comprise a blog application:
  12. .. _queryset-model-example:
  13. .. code-block:: python
  14. from datetime import date
  15. from django.db import models
  16. class Blog(models.Model):
  17. name = models.CharField(max_length=100)
  18. tagline = models.TextField()
  19. def __str__(self):
  20. return self.name
  21. class Author(models.Model):
  22. name = models.CharField(max_length=200)
  23. email = models.EmailField()
  24. def __str__(self):
  25. return self.name
  26. class Entry(models.Model):
  27. blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
  28. headline = models.CharField(max_length=255)
  29. body_text = models.TextField()
  30. pub_date = models.DateField()
  31. mod_date = models.DateField(default=date.today)
  32. authors = models.ManyToManyField(Author)
  33. number_of_comments = models.IntegerField(default=0)
  34. number_of_pingbacks = models.IntegerField(default=0)
  35. rating = models.IntegerField(default=5)
  36. def __str__(self):
  37. return self.headline
  38. Creating objects
  39. ================
  40. To represent database-table data in Python objects, Django uses an intuitive
  41. system: A model class represents a database table, and an instance of that
  42. class represents a particular record in the database table.
  43. To create an object, instantiate it using keyword arguments to the model class,
  44. then call :meth:`~django.db.models.Model.save` to save it to the database.
  45. Assuming models live in a ``models.py`` file inside a ``blog`` Django app, here
  46. is an example:
  47. .. code-block:: pycon
  48. >>> from blog.models import Blog
  49. >>> b = Blog(name="Beatles Blog", tagline="All the latest Beatles news.")
  50. >>> b.save()
  51. This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
  52. the database until you explicitly call :meth:`~django.db.models.Model.save`.
  53. The :meth:`~django.db.models.Model.save` method has no return value.
  54. .. seealso::
  55. :meth:`~django.db.models.Model.save` takes a number of advanced options not
  56. described here. See the documentation for
  57. :meth:`~django.db.models.Model.save` for complete details.
  58. To create and save an object in a single step, use the
  59. :meth:`~django.db.models.query.QuerySet.create()` method.
  60. Saving changes to objects
  61. =========================
  62. To save changes to an object that's already in the database, use
  63. :meth:`~django.db.models.Model.save`.
  64. Given a ``Blog`` instance ``b5`` that has already been saved to the database,
  65. this example changes its name and updates its record in the database:
  66. .. code-block:: pycon
  67. >>> b5.name = "New name"
  68. >>> b5.save()
  69. This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
  70. the database until you explicitly call :meth:`~django.db.models.Model.save`.
  71. Saving ``ForeignKey`` and ``ManyToManyField`` fields
  72. ----------------------------------------------------
  73. Updating a :class:`~django.db.models.ForeignKey` field works exactly the same
  74. way as saving a normal field -- assign an object of the right type to the field
  75. in question. This example updates the ``blog`` attribute of an ``Entry``
  76. instance ``entry``, assuming appropriate instances of ``Entry`` and ``Blog``
  77. are already saved to the database (so we can retrieve them below):
  78. .. code-block:: pycon
  79. >>> from blog.models import Blog, Entry
  80. >>> entry = Entry.objects.get(pk=1)
  81. >>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
  82. >>> entry.blog = cheese_blog
  83. >>> entry.save()
  84. Updating a :class:`~django.db.models.ManyToManyField` works a little
  85. differently -- use the
  86. :meth:`~django.db.models.fields.related.RelatedManager.add` method on the field
  87. to add a record to the relation. This example adds the ``Author`` instance
  88. ``joe`` to the ``entry`` object:
  89. .. code-block:: pycon
  90. >>> from blog.models import Author
  91. >>> joe = Author.objects.create(name="Joe")
  92. >>> entry.authors.add(joe)
  93. To add multiple records to a :class:`~django.db.models.ManyToManyField` in one
  94. go, include multiple arguments in the call to
  95. :meth:`~django.db.models.fields.related.RelatedManager.add`, like this:
  96. .. code-block:: pycon
  97. >>> john = Author.objects.create(name="John")
  98. >>> paul = Author.objects.create(name="Paul")
  99. >>> george = Author.objects.create(name="George")
  100. >>> ringo = Author.objects.create(name="Ringo")
  101. >>> entry.authors.add(john, paul, george, ringo)
  102. Django will complain if you try to assign or add an object of the wrong type.
  103. .. _retrieving-objects:
  104. Retrieving objects
  105. ==================
  106. To retrieve objects from your database, construct a
  107. :class:`~django.db.models.query.QuerySet` via a
  108. :class:`~django.db.models.Manager` on your model class.
  109. A :class:`~django.db.models.query.QuerySet` represents a collection of objects
  110. from your database. It can have zero, one or many *filters*. Filters narrow
  111. down the query results based on the given parameters. In SQL terms, a
  112. :class:`~django.db.models.query.QuerySet` equates to a ``SELECT`` statement,
  113. and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
  114. You get a :class:`~django.db.models.query.QuerySet` by using your model's
  115. :class:`~django.db.models.Manager`. Each model has at least one
  116. :class:`~django.db.models.Manager`, and it's called
  117. :attr:`~django.db.models.Model.objects` by default. Access it directly via the
  118. model class, like so:
  119. .. code-block:: pycon
  120. >>> Blog.objects
  121. <django.db.models.manager.Manager object at ...>
  122. >>> b = Blog(name="Foo", tagline="Bar")
  123. >>> b.objects
  124. Traceback:
  125. ...
  126. AttributeError: "Manager isn't accessible via Blog instances."
  127. .. note::
  128. ``Managers`` are accessible only via model classes, rather than from model
  129. instances, to enforce a separation between "table-level" operations and
  130. "record-level" operations.
  131. The :class:`~django.db.models.Manager` is the main source of ``QuerySets`` for
  132. a model. For example, ``Blog.objects.all()`` returns a
  133. :class:`~django.db.models.query.QuerySet` that contains all ``Blog`` objects in
  134. the database.
  135. Retrieving all objects
  136. ----------------------
  137. The simplest way to retrieve objects from a table is to get all of them. To do
  138. this, use the :meth:`~django.db.models.query.QuerySet.all` method on a
  139. :class:`~django.db.models.Manager`:
  140. .. code-block:: pycon
  141. >>> all_entries = Entry.objects.all()
  142. The :meth:`~django.db.models.query.QuerySet.all` method returns a
  143. :class:`~django.db.models.query.QuerySet` of all the objects in the database.
  144. Retrieving specific objects with filters
  145. ----------------------------------------
  146. The :class:`~django.db.models.query.QuerySet` returned by
  147. :meth:`~django.db.models.query.QuerySet.all` describes all objects in the
  148. database table. Usually, though, you'll need to select only a subset of the
  149. complete set of objects.
  150. To create such a subset, you refine the initial
  151. :class:`~django.db.models.query.QuerySet`, adding filter conditions. The two
  152. most common ways to refine a :class:`~django.db.models.query.QuerySet` are:
  153. ``filter(**kwargs)``
  154. Returns a new :class:`~django.db.models.query.QuerySet` containing objects
  155. that match the given lookup parameters.
  156. ``exclude(**kwargs)``
  157. Returns a new :class:`~django.db.models.query.QuerySet` containing objects
  158. that do *not* match the given lookup parameters.
  159. The lookup parameters (``**kwargs`` in the above function definitions) should
  160. be in the format described in `Field lookups`_ below.
  161. For example, to get a :class:`~django.db.models.query.QuerySet` of blog entries
  162. from the year 2006, use :meth:`~django.db.models.query.QuerySet.filter` like
  163. so::
  164. Entry.objects.filter(pub_date__year=2006)
  165. With the default manager class, it is the same as::
  166. Entry.objects.all().filter(pub_date__year=2006)
  167. .. _chaining-filters:
  168. Chaining filters
  169. ~~~~~~~~~~~~~~~~
  170. The result of refining a :class:`~django.db.models.query.QuerySet` is itself a
  171. :class:`~django.db.models.query.QuerySet`, so it's possible to chain
  172. refinements together. For example:
  173. .. code-block:: pycon
  174. >>> Entry.objects.filter(headline__startswith="What").exclude(
  175. ... pub_date__gte=datetime.date.today()
  176. ... ).filter(pub_date__gte=datetime.date(2005, 1, 30))
  177. This takes the initial :class:`~django.db.models.query.QuerySet` of all entries
  178. in the database, adds a filter, then an exclusion, then another filter. The
  179. final result is a :class:`~django.db.models.query.QuerySet` containing all
  180. entries with a headline that starts with "What", that were published between
  181. January 30, 2005, and the current day.
  182. .. _filtered-querysets-are-unique:
  183. Filtered ``QuerySet``\s are unique
  184. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  185. Each time you refine a :class:`~django.db.models.query.QuerySet`, you get a
  186. brand-new :class:`~django.db.models.query.QuerySet` that is in no way bound to
  187. the previous :class:`~django.db.models.query.QuerySet`. Each refinement creates
  188. a separate and distinct :class:`~django.db.models.query.QuerySet` that can be
  189. stored, used and reused.
  190. Example:
  191. .. code-block:: pycon
  192. >>> q1 = Entry.objects.filter(headline__startswith="What")
  193. >>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
  194. >>> q3 = q1.filter(pub_date__gte=datetime.date.today())
  195. These three ``QuerySets`` are separate. The first is a base
  196. :class:`~django.db.models.query.QuerySet` containing all entries that contain a
  197. headline starting with "What". The second is a subset of the first, with an
  198. additional criteria that excludes records whose ``pub_date`` is today or in the
  199. future. The third is a subset of the first, with an additional criteria that
  200. selects only the records whose ``pub_date`` is today or in the future. The
  201. initial :class:`~django.db.models.query.QuerySet` (``q1``) is unaffected by the
  202. refinement process.
  203. .. _querysets-are-lazy:
  204. ``QuerySet``\s are lazy
  205. ~~~~~~~~~~~~~~~~~~~~~~~
  206. ``QuerySets`` are lazy -- the act of creating a
  207. :class:`~django.db.models.query.QuerySet` doesn't involve any database
  208. activity. You can stack filters together all day long, and Django won't
  209. actually run the query until the :class:`~django.db.models.query.QuerySet` is
  210. *evaluated*. Take a look at this example:
  211. .. code-block:: pycon
  212. >>> q = Entry.objects.filter(headline__startswith="What")
  213. >>> q = q.filter(pub_date__lte=datetime.date.today())
  214. >>> q = q.exclude(body_text__icontains="food")
  215. >>> print(q)
  216. Though this looks like three database hits, in fact it hits the database only
  217. once, at the last line (``print(q)``). In general, the results of a
  218. :class:`~django.db.models.query.QuerySet` aren't fetched from the database
  219. until you "ask" for them. When you do, the
  220. :class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the
  221. database. For more details on exactly when evaluation takes place, see
  222. :ref:`when-querysets-are-evaluated`.
  223. .. _retrieving-single-object-with-get:
  224. Retrieving a single object with ``get()``
  225. -----------------------------------------
  226. :meth:`~django.db.models.query.QuerySet.filter` will always give you a
  227. :class:`~django.db.models.query.QuerySet`, even if only a single object matches
  228. the query - in this case, it will be a
  229. :class:`~django.db.models.query.QuerySet` containing a single element.
  230. If you know there is only one object that matches your query, you can use the
  231. :meth:`~django.db.models.query.QuerySet.get` method on a
  232. :class:`~django.db.models.Manager` which returns the object directly:
  233. .. code-block:: pycon
  234. >>> one_entry = Entry.objects.get(pk=1)
  235. You can use any query expression with
  236. :meth:`~django.db.models.query.QuerySet.get`, just like with
  237. :meth:`~django.db.models.query.QuerySet.filter` - again, see `Field lookups`_
  238. below.
  239. Note that there is a difference between using
  240. :meth:`~django.db.models.query.QuerySet.get`, and using
  241. :meth:`~django.db.models.query.QuerySet.filter` with a slice of ``[0]``. If
  242. there are no results that match the query,
  243. :meth:`~django.db.models.query.QuerySet.get` will raise a ``DoesNotExist``
  244. exception. This exception is an attribute of the model class that the query is
  245. being performed on - so in the code above, if there is no ``Entry`` object with
  246. a primary key of 1, Django will raise ``Entry.DoesNotExist``.
  247. Similarly, Django will complain if more than one item matches the
  248. :meth:`~django.db.models.query.QuerySet.get` query. In this case, it will raise
  249. :exc:`~django.core.exceptions.MultipleObjectsReturned`, which again is an
  250. attribute of the model class itself.
  251. Other ``QuerySet`` methods
  252. --------------------------
  253. Most of the time you'll use :meth:`~django.db.models.query.QuerySet.all`,
  254. :meth:`~django.db.models.query.QuerySet.get`,
  255. :meth:`~django.db.models.query.QuerySet.filter` and
  256. :meth:`~django.db.models.query.QuerySet.exclude` when you need to look up
  257. objects from the database. However, that's far from all there is; see the
  258. :ref:`QuerySet API Reference <queryset-api>` for a complete list of all the
  259. various :class:`~django.db.models.query.QuerySet` methods.
  260. .. _limiting-querysets:
  261. Limiting ``QuerySet``\s
  262. -----------------------
  263. Use a subset of Python's array-slicing syntax to limit your
  264. :class:`~django.db.models.query.QuerySet` to a certain number of results. This
  265. is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
  266. For example, this returns the first 5 objects (``LIMIT 5``):
  267. .. code-block:: pycon
  268. >>> Entry.objects.all()[:5]
  269. This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``):
  270. .. code-block:: pycon
  271. >>> Entry.objects.all()[5:10]
  272. Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported.
  273. Generally, slicing a :class:`~django.db.models.query.QuerySet` returns a new
  274. :class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An
  275. exception is if you use the "step" parameter of Python slice syntax. For
  276. example, this would actually execute the query in order to return a list of
  277. every *second* object of the first 10:
  278. .. code-block:: pycon
  279. >>> Entry.objects.all()[:10:2]
  280. Further filtering or ordering of a sliced queryset is prohibited due to the
  281. ambiguous nature of how that might work.
  282. To retrieve a *single* object rather than a list
  283. (e.g. ``SELECT foo FROM bar LIMIT 1``), use an index instead of a slice. For
  284. example, this returns the first ``Entry`` in the database, after ordering
  285. entries alphabetically by headline:
  286. .. code-block:: pycon
  287. >>> Entry.objects.order_by("headline")[0]
  288. This is roughly equivalent to:
  289. .. code-block:: pycon
  290. >>> Entry.objects.order_by("headline")[0:1].get()
  291. Note, however, that the first of these will raise ``IndexError`` while the
  292. second will raise ``DoesNotExist`` if no objects match the given criteria. See
  293. :meth:`~django.db.models.query.QuerySet.get` for more details.
  294. .. _field-lookups-intro:
  295. Field lookups
  296. -------------
  297. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
  298. specified as keyword arguments to the :class:`~django.db.models.query.QuerySet`
  299. methods :meth:`~django.db.models.query.QuerySet.filter`,
  300. :meth:`~django.db.models.query.QuerySet.exclude` and
  301. :meth:`~django.db.models.query.QuerySet.get`.
  302. Basic lookups keyword arguments take the form ``field__lookuptype=value``.
  303. (That's a double-underscore). For example:
  304. .. code-block:: pycon
  305. >>> Entry.objects.filter(pub_date__lte="2006-01-01")
  306. translates (roughly) into the following SQL:
  307. .. code-block:: sql
  308. SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
  309. .. admonition:: How this is possible
  310. Python has the ability to define functions that accept arbitrary name-value
  311. arguments whose names and values are evaluated at runtime. For more
  312. information, see :ref:`tut-keywordargs` in the official Python tutorial.
  313. The field specified in a lookup has to be the name of a model field. There's
  314. one exception though, in case of a :class:`~django.db.models.ForeignKey` you
  315. can specify the field name suffixed with ``_id``. In this case, the value
  316. parameter is expected to contain the raw value of the foreign model's primary
  317. key. For example:
  318. .. code-block:: pycon
  319. >>> Entry.objects.filter(blog_id=4)
  320. If you pass an invalid keyword argument, a lookup function will raise
  321. ``TypeError``.
  322. The database API supports about two dozen lookup types; a complete reference
  323. can be found in the :ref:`field lookup reference <field-lookups>`. To give you
  324. a taste of what's available, here's some of the more common lookups you'll
  325. probably use:
  326. :lookup:`exact`
  327. An "exact" match. For example:
  328. .. code-block:: pycon
  329. >>> Entry.objects.get(headline__exact="Cat bites dog")
  330. Would generate SQL along these lines:
  331. .. code-block:: sql
  332. SELECT ... WHERE headline = 'Cat bites dog';
  333. If you don't provide a lookup type -- that is, if your keyword argument
  334. doesn't contain a double underscore -- the lookup type is assumed to be
  335. ``exact``.
  336. For example, the following two statements are equivalent:
  337. .. code-block:: pycon
  338. >>> Blog.objects.get(id__exact=14) # Explicit form
  339. >>> Blog.objects.get(id=14) # __exact is implied
  340. This is for convenience, because ``exact`` lookups are the common case.
  341. :lookup:`iexact`
  342. A case-insensitive match. So, the query:
  343. .. code-block:: pycon
  344. >>> Blog.objects.get(name__iexact="beatles blog")
  345. Would match a ``Blog`` titled ``"Beatles Blog"``, ``"beatles blog"``, or
  346. even ``"BeAtlES blOG"``.
  347. :lookup:`contains`
  348. Case-sensitive containment test. For example::
  349. Entry.objects.get(headline__contains="Lennon")
  350. Roughly translates to this SQL:
  351. .. code-block:: sql
  352. SELECT ... WHERE headline LIKE '%Lennon%';
  353. Note this will match the headline ``'Today Lennon honored'`` but not
  354. ``'today lennon honored'``.
  355. There's also a case-insensitive version, :lookup:`icontains`.
  356. :lookup:`startswith`, :lookup:`endswith`
  357. Starts-with and ends-with search, respectively. There are also
  358. case-insensitive versions called :lookup:`istartswith` and
  359. :lookup:`iendswith`.
  360. Again, this only scratches the surface. A complete reference can be found in the
  361. :ref:`field lookup reference <field-lookups>`.
  362. .. _lookups-that-span-relationships:
  363. Lookups that span relationships
  364. -------------------------------
  365. Django offers a powerful and intuitive way to "follow" relationships in
  366. lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
  367. scenes. To span a relationship, use the field name of related fields
  368. across models, separated by double underscores, until you get to the field you
  369. want.
  370. This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
  371. is ``'Beatles Blog'``:
  372. .. code-block:: pycon
  373. >>> Entry.objects.filter(blog__name="Beatles Blog")
  374. This spanning can be as deep as you'd like.
  375. It works backwards, too. While it :attr:`can be customized
  376. <.ForeignKey.related_query_name>`, by default you refer to a "reverse"
  377. relationship in a lookup using the lowercase name of the model.
  378. This example retrieves all ``Blog`` objects which have at least one ``Entry``
  379. whose ``headline`` contains ``'Lennon'``:
  380. .. code-block:: pycon
  381. >>> Blog.objects.filter(entry__headline__contains="Lennon")
  382. If you are filtering across multiple relationships and one of the intermediate
  383. models doesn't have a value that meets the filter condition, Django will treat
  384. it as if there is an empty (all values are ``NULL``), but valid, object there.
  385. All this means is that no error will be raised. For example, in this filter::
  386. Blog.objects.filter(entry__authors__name="Lennon")
  387. (if there was a related ``Author`` model), if there was no ``author``
  388. associated with an entry, it would be treated as if there was also no ``name``
  389. attached, rather than raising an error because of the missing ``author``.
  390. Usually this is exactly what you want to have happen. The only case where it
  391. might be confusing is if you are using :lookup:`isnull`. Thus::
  392. Blog.objects.filter(entry__authors__name__isnull=True)
  393. will return ``Blog`` objects that have an empty ``name`` on the ``author`` and
  394. also those which have an empty ``author`` on the ``entry``. If you don't want
  395. those latter objects, you could write::
  396. Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
  397. .. _spanning-multi-valued-relationships:
  398. Spanning multi-valued relationships
  399. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  400. When spanning a :class:`~django.db.models.ManyToManyField` or a reverse
  401. :class:`~django.db.models.ForeignKey` (such as from ``Blog`` to ``Entry``),
  402. filtering on multiple attributes raises the question of whether to require each
  403. attribute to coincide in the same related object. We might seek blogs that have
  404. an entry from 2008 with *“Lennon”* in its headline, or we might seek blogs that
  405. merely have any entry from 2008 as well as some newer or older entry with
  406. *“Lennon”* in its headline.
  407. To select all blogs containing at least one entry from 2008 having *"Lennon"*
  408. in its headline (the same entry satisfying both conditions), we would write::
  409. Blog.objects.filter(entry__headline__contains="Lennon", entry__pub_date__year=2008)
  410. Otherwise, to perform a more permissive query selecting any blogs with merely
  411. *some* entry with *"Lennon"* in its headline and *some* entry from 2008, we
  412. would write::
  413. Blog.objects.filter(entry__headline__contains="Lennon").filter(
  414. entry__pub_date__year=2008
  415. )
  416. Suppose there is only one blog that has both entries containing *"Lennon"* and
  417. entries from 2008, but that none of the entries from 2008 contained *"Lennon"*.
  418. The first query would not return any blogs, but the second query would return
  419. that one blog. (This is because the entries selected by the second filter may
  420. or may not be the same as the entries in the first filter. We are filtering the
  421. ``Blog`` items with each filter statement, not the ``Entry`` items.) In short,
  422. if each condition needs to match the same related object, then each should be
  423. contained in a single :meth:`~django.db.models.query.QuerySet.filter` call.
  424. .. note::
  425. As the second (more permissive) query chains multiple filters, it performs
  426. multiple joins to the primary model, potentially yielding duplicates.
  427. .. code-block:: pycon
  428. >>> from datetime import date
  429. >>> beatles = Blog.objects.create(name="Beatles Blog")
  430. >>> pop = Blog.objects.create(name="Pop Music Blog")
  431. >>> Entry.objects.create(
  432. ... blog=beatles,
  433. ... headline="New Lennon Biography",
  434. ... pub_date=date(2008, 6, 1),
  435. ... )
  436. <Entry: New Lennon Biography>
  437. >>> Entry.objects.create(
  438. ... blog=beatles,
  439. ... headline="New Lennon Biography in Paperback",
  440. ... pub_date=date(2009, 6, 1),
  441. ... )
  442. <Entry: New Lennon Biography in Paperback>
  443. >>> Entry.objects.create(
  444. ... blog=pop,
  445. ... headline="Best Albums of 2008",
  446. ... pub_date=date(2008, 12, 15),
  447. ... )
  448. <Entry: Best Albums of 2008>
  449. >>> Entry.objects.create(
  450. ... blog=pop,
  451. ... headline="Lennon Would Have Loved Hip Hop",
  452. ... pub_date=date(2020, 4, 1),
  453. ... )
  454. <Entry: Lennon Would Have Loved Hip Hop>
  455. >>> Blog.objects.filter(
  456. ... entry__headline__contains="Lennon",
  457. ... entry__pub_date__year=2008,
  458. ... )
  459. <QuerySet [<Blog: Beatles Blog>]>
  460. >>> Blog.objects.filter(
  461. ... entry__headline__contains="Lennon",
  462. ... ).filter(
  463. ... entry__pub_date__year=2008,
  464. ... )
  465. <QuerySet [<Blog: Beatles Blog>, <Blog: Beatles Blog>, <Blog: Pop Music Blog]>
  466. .. note::
  467. The behavior of :meth:`~django.db.models.query.QuerySet.filter` for queries
  468. that span multi-value relationships, as described above, is not implemented
  469. equivalently for :meth:`~django.db.models.query.QuerySet.exclude`. Instead,
  470. the conditions in a single :meth:`~django.db.models.query.QuerySet.exclude`
  471. call will not necessarily refer to the same item.
  472. For example, the following query would exclude blogs that contain *both*
  473. entries with *"Lennon"* in the headline *and* entries published in 2008::
  474. Blog.objects.exclude(
  475. entry__headline__contains="Lennon",
  476. entry__pub_date__year=2008,
  477. )
  478. However, unlike the behavior when using
  479. :meth:`~django.db.models.query.QuerySet.filter`, this will not limit blogs
  480. based on entries that satisfy both conditions. In order to do that, i.e.
  481. to select all blogs that do not contain entries published with *"Lennon"*
  482. that were published in 2008, you need to make two queries::
  483. Blog.objects.exclude(
  484. entry__in=Entry.objects.filter(
  485. headline__contains="Lennon",
  486. pub_date__year=2008,
  487. ),
  488. )
  489. .. _using-f-expressions-in-filters:
  490. Filters can reference fields on the model
  491. -----------------------------------------
  492. In the examples given so far, we have constructed filters that compare
  493. the value of a model field with a constant. But what if you want to compare
  494. the value of a model field with another field on the same model?
  495. Django provides :class:`F expressions <django.db.models.F>` to allow such
  496. comparisons. Instances of ``F()`` act as a reference to a model field within a
  497. query. These references can then be used in query filters to compare the values
  498. of two different fields on the same model instance.
  499. For example, to find a list of all blog entries that have had more comments
  500. than pingbacks, we construct an ``F()`` object to reference the pingback count,
  501. and use that ``F()`` object in the query:
  502. .. code-block:: pycon
  503. >>> from django.db.models import F
  504. >>> Entry.objects.filter(number_of_comments__gt=F("number_of_pingbacks"))
  505. Django supports the use of addition, subtraction, multiplication,
  506. division, modulo, and power arithmetic with ``F()`` objects, both with constants
  507. and with other ``F()`` objects. To find all the blog entries with more than
  508. *twice* as many comments as pingbacks, we modify the query:
  509. .. code-block:: pycon
  510. >>> Entry.objects.filter(number_of_comments__gt=F("number_of_pingbacks") * 2)
  511. To find all the entries where the rating of the entry is less than the
  512. sum of the pingback count and comment count, we would issue the
  513. query:
  514. .. code-block:: pycon
  515. >>> Entry.objects.filter(rating__lt=F("number_of_comments") + F("number_of_pingbacks"))
  516. You can also use the double underscore notation to span relationships in
  517. an ``F()`` object. An ``F()`` object with a double underscore will introduce
  518. any joins needed to access the related object. For example, to retrieve all
  519. the entries where the author's name is the same as the blog name, we could
  520. issue the query:
  521. .. code-block:: pycon
  522. >>> Entry.objects.filter(authors__name=F("blog__name"))
  523. For date and date/time fields, you can add or subtract a
  524. :class:`~datetime.timedelta` object. The following would return all entries
  525. that were modified more than 3 days after they were published:
  526. .. code-block:: pycon
  527. >>> from datetime import timedelta
  528. >>> Entry.objects.filter(mod_date__gt=F("pub_date") + timedelta(days=3))
  529. The ``F()`` objects support bitwise operations by ``.bitand()``, ``.bitor()``,
  530. ``.bitxor()``, ``.bitrightshift()``, and ``.bitleftshift()``. For example:
  531. .. code-block:: pycon
  532. >>> F("somefield").bitand(16)
  533. .. admonition:: Oracle
  534. Oracle doesn't support bitwise XOR operation.
  535. .. _using-transforms-in-expressions:
  536. Expressions can reference transforms
  537. ------------------------------------
  538. Django supports using transforms in expressions.
  539. For example, to find all ``Entry`` objects published in the same year as they
  540. were last modified:
  541. .. code-block:: pycon
  542. >>> from django.db.models import F
  543. >>> Entry.objects.filter(pub_date__year=F("mod_date__year"))
  544. To find the earliest year an entry was published, we can issue the query:
  545. .. code-block:: pycon
  546. >>> from django.db.models import Min
  547. >>> Entry.objects.aggregate(first_published_year=Min("pub_date__year"))
  548. This example finds the value of the highest rated entry and the total number
  549. of comments on all entries for each year:
  550. .. code-block:: pycon
  551. >>> from django.db.models import OuterRef, Subquery, Sum
  552. >>> Entry.objects.values("pub_date__year").annotate(
  553. ... top_rating=Subquery(
  554. ... Entry.objects.filter(
  555. ... pub_date__year=OuterRef("pub_date__year"),
  556. ... )
  557. ... .order_by("-rating")
  558. ... .values("rating")[:1]
  559. ... ),
  560. ... total_comments=Sum("number_of_comments"),
  561. ... )
  562. The ``pk`` lookup shortcut
  563. --------------------------
  564. For convenience, Django provides a ``pk`` lookup shortcut, which stands for
  565. "primary key".
  566. In the example ``Blog`` model, the primary key is the ``id`` field, so these
  567. three statements are equivalent:
  568. .. code-block:: pycon
  569. >>> Blog.objects.get(id__exact=14) # Explicit form
  570. >>> Blog.objects.get(id=14) # __exact is implied
  571. >>> Blog.objects.get(pk=14) # pk implies id__exact
  572. The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
  573. can be combined with ``pk`` to perform a query on the primary key of a model:
  574. .. code-block:: pycon
  575. # Get blogs entries with id 1, 4 and 7
  576. >>> Blog.objects.filter(pk__in=[1, 4, 7])
  577. # Get all blog entries with id > 14
  578. >>> Blog.objects.filter(pk__gt=14)
  579. ``pk`` lookups also work across joins. For example, these three statements are
  580. equivalent:
  581. .. code-block:: pycon
  582. >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
  583. >>> Entry.objects.filter(blog__id=3) # __exact is implied
  584. >>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
  585. Escaping percent signs and underscores in ``LIKE`` statements
  586. -------------------------------------------------------------
  587. The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
  588. ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
  589. and ``iendswith``) will automatically escape the two special characters used in
  590. ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
  591. statement, the percent sign signifies a multiple-character wildcard and the
  592. underscore signifies a single-character wildcard.)
  593. This means things should work intuitively, so the abstraction doesn't leak.
  594. For example, to retrieve all the entries that contain a percent sign, use the
  595. percent sign as any other character:
  596. .. code-block:: pycon
  597. >>> Entry.objects.filter(headline__contains="%")
  598. Django takes care of the quoting for you; the resulting SQL will look something
  599. like this:
  600. .. code-block:: sql
  601. SELECT ... WHERE headline LIKE '%\%%';
  602. Same goes for underscores. Both percentage signs and underscores are handled
  603. for you transparently.
  604. .. _caching-and-querysets:
  605. Caching and ``QuerySet``\s
  606. --------------------------
  607. Each :class:`~django.db.models.query.QuerySet` contains a cache to minimize
  608. database access. Understanding how it works will allow you to write the most
  609. efficient code.
  610. In a newly created :class:`~django.db.models.query.QuerySet`, the cache is
  611. empty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated
  612. -- and, hence, a database query happens -- Django saves the query results in
  613. the :class:`~django.db.models.query.QuerySet`’s cache and returns the results
  614. that have been explicitly requested (e.g., the next element, if the
  615. :class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent
  616. evaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached
  617. results.
  618. Keep this caching behavior in mind, because it may bite you if you don't use
  619. your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
  620. following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
  621. them, and throw them away:
  622. .. code-block:: pycon
  623. >>> print([e.headline for e in Entry.objects.all()])
  624. >>> print([e.pub_date for e in Entry.objects.all()])
  625. That means the same database query will be executed twice, effectively doubling
  626. your database load. Also, there's a possibility the two lists may not include
  627. the same database records, because an ``Entry`` may have been added or deleted
  628. in the split second between the two requests.
  629. To avoid this problem, save the :class:`~django.db.models.query.QuerySet` and
  630. reuse it:
  631. .. code-block:: pycon
  632. >>> queryset = Entry.objects.all()
  633. >>> print([p.headline for p in queryset]) # Evaluate the query set.
  634. >>> print([p.pub_date for p in queryset]) # Reuse the cache from the evaluation.
  635. When ``QuerySet``\s are not cached
  636. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  637. Querysets do not always cache their results. When evaluating only *part* of
  638. the queryset, the cache is checked, but if it is not populated then the items
  639. returned by the subsequent query are not cached. Specifically, this means that
  640. :ref:`limiting the queryset <limiting-querysets>` using an array slice or an
  641. index will not populate the cache.
  642. For example, repeatedly getting a certain index in a queryset object will query
  643. the database each time:
  644. .. code-block:: pycon
  645. >>> queryset = Entry.objects.all()
  646. >>> print(queryset[5]) # Queries the database
  647. >>> print(queryset[5]) # Queries the database again
  648. However, if the entire queryset has already been evaluated, the cache will be
  649. checked instead:
  650. .. code-block:: pycon
  651. >>> queryset = Entry.objects.all()
  652. >>> [entry for entry in queryset] # Queries the database
  653. >>> print(queryset[5]) # Uses cache
  654. >>> print(queryset[5]) # Uses cache
  655. Here are some examples of other actions that will result in the entire queryset
  656. being evaluated and therefore populate the cache:
  657. .. code-block:: pycon
  658. >>> [entry for entry in queryset]
  659. >>> bool(queryset)
  660. >>> entry in queryset
  661. >>> list(queryset)
  662. .. note::
  663. Simply printing the queryset will not populate the cache. This is because
  664. the call to ``__repr__()`` only returns a slice of the entire queryset.
  665. .. _async-queries:
  666. Asynchronous queries
  667. ====================
  668. If you are writing asynchronous views or code, you cannot use the ORM for
  669. queries in quite the way we have described above, as you cannot call *blocking*
  670. synchronous code from asynchronous code - it will block up the event loop
  671. (or, more likely, Django will notice and raise a ``SynchronousOnlyOperation``
  672. to stop that from happening).
  673. Fortunately, you can do many queries using Django's asynchronous query APIs.
  674. Every method that might block - such as ``get()`` or ``delete()`` - has an
  675. asynchronous variant (``aget()`` or ``adelete()``), and when you iterate over
  676. results, you can use asynchronous iteration (``async for``) instead.
  677. Query iteration
  678. ---------------
  679. The default way of iterating over a query - with ``for`` - will result in a
  680. blocking database query behind the scenes as Django loads the results at
  681. iteration time. To fix this, you can swap to ``async for``::
  682. async for entry in Authors.objects.filter(name__startswith="A"):
  683. ...
  684. Be aware that you also can't do other things that might iterate over the
  685. queryset, such as wrapping ``list()`` around it to force its evaluation (you
  686. can use ``async for`` in a comprehension, if you want it).
  687. Because ``QuerySet`` methods like ``filter()`` and ``exclude()`` do not
  688. actually run the query - they set up the queryset to run when it's iterated
  689. over - you can use those freely in asynchronous code. For a guide to which
  690. methods can keep being used like this, and which have asynchronous versions,
  691. read the next section.
  692. ``QuerySet`` and manager methods
  693. --------------------------------
  694. Some methods on managers and querysets - like ``get()`` and ``first()`` - force
  695. execution of the queryset and are blocking. Some, like ``filter()`` and
  696. ``exclude()``, don't force execution and so are safe to run from asynchronous
  697. code. But how are you supposed to tell the difference?
  698. While you could poke around and see if there is an ``a``-prefixed version of
  699. the method (for example, we have ``aget()`` but not ``afilter()``), there is a
  700. more logical way - look up what kind of method it is in the
  701. :doc:`QuerySet reference </ref/models/querysets>`.
  702. In there, you'll find the methods on QuerySets grouped into two sections:
  703. * *Methods that return new querysets*: These are the non-blocking ones,
  704. and don't have asynchronous versions. You're free to use these in any
  705. situation, though read the notes on ``defer()`` and ``only()`` before you use
  706. them.
  707. * *Methods that do not return querysets*: These are the blocking ones, and
  708. have asynchronous versions - the asynchronous name for each is noted in its
  709. documentation, though our standard pattern is to add an ``a`` prefix.
  710. Using this distinction, you can work out when you need to use asynchronous
  711. versions, and when you don't. For example, here's a valid asynchronous query::
  712. user = await User.objects.filter(username=my_input).afirst()
  713. ``filter()`` returns a queryset, and so it's fine to keep chaining it inside an
  714. asynchronous environment, whereas ``first()`` evaluates and returns a model
  715. instance - thus, we change to ``afirst()``, and use ``await`` at the front of
  716. the whole expression in order to call it in an asynchronous-friendly way.
  717. .. note::
  718. If you forget to put the ``await`` part in, you may see errors like
  719. *"coroutine object has no attribute x"* or *"<coroutine …>"* strings in
  720. place of your model instances. If you ever see these, you are missing an
  721. ``await`` somewhere to turn that coroutine into a real value.
  722. Transactions
  723. ------------
  724. Transactions are **not** currently supported with asynchronous queries and
  725. updates. You will find that trying to use one raises
  726. ``SynchronousOnlyOperation``.
  727. If you wish to use a transaction, we suggest you write your ORM code inside a
  728. separate, synchronous function and then call that using ``sync_to_async`` - see
  729. :doc:`/topics/async` for more.
  730. .. _querying-jsonfield:
  731. Querying ``JSONField``
  732. ======================
  733. Lookups implementation is different in :class:`~django.db.models.JSONField`,
  734. mainly due to the existence of key transformations. To demonstrate, we will use
  735. the following example model::
  736. from django.db import models
  737. class Dog(models.Model):
  738. name = models.CharField(max_length=200)
  739. data = models.JSONField(null=True)
  740. def __str__(self):
  741. return self.name
  742. Storing and querying for ``None``
  743. ---------------------------------
  744. As with other fields, storing ``None`` as the field's value will store it as
  745. SQL ``NULL``. While not recommended, it is possible to store JSON scalar
  746. ``null`` instead of SQL ``NULL`` by using :class:`Value(None, JSONField())
  747. <django.db.models.Value>`.
  748. Whichever of the values is stored, when retrieved from the database, the Python
  749. representation of the JSON scalar ``null`` is the same as SQL ``NULL``, i.e.
  750. ``None``. Therefore, it can be hard to distinguish between them.
  751. This only applies to ``None`` as the top-level value of the field. If ``None``
  752. is inside a :py:class:`list` or :py:class:`dict`, it will always be interpreted
  753. as JSON ``null``.
  754. When querying, ``None`` value will always be interpreted as JSON ``null``. To
  755. query for SQL ``NULL``, use :lookup:`isnull`:
  756. .. code-block:: pycon
  757. >>> Dog.objects.create(name="Max", data=None) # SQL NULL.
  758. <Dog: Max>
  759. >>> Dog.objects.create(name="Archie", data=Value(None, JSONField())) # JSON null.
  760. <Dog: Archie>
  761. >>> Dog.objects.filter(data=None)
  762. <QuerySet [<Dog: Archie>]>
  763. >>> Dog.objects.filter(data=Value(None, JSONField()))
  764. <QuerySet [<Dog: Archie>]>
  765. >>> Dog.objects.filter(data__isnull=True)
  766. <QuerySet [<Dog: Max>]>
  767. >>> Dog.objects.filter(data__isnull=False)
  768. <QuerySet [<Dog: Archie>]>
  769. Unless you are sure you wish to work with SQL ``NULL`` values, consider setting
  770. ``null=False`` and providing a suitable default for empty values, such as
  771. ``default=dict``.
  772. .. note::
  773. Storing JSON scalar ``null`` does not violate :attr:`null=False
  774. <django.db.models.Field.null>`.
  775. .. fieldlookup:: jsonfield.key
  776. Key, index, and path transforms
  777. -------------------------------
  778. To query based on a given dictionary key, use that key as the lookup name:
  779. .. code-block:: pycon
  780. >>> Dog.objects.create(
  781. ... name="Rufus",
  782. ... data={
  783. ... "breed": "labrador",
  784. ... "owner": {
  785. ... "name": "Bob",
  786. ... "other_pets": [
  787. ... {
  788. ... "name": "Fishy",
  789. ... }
  790. ... ],
  791. ... },
  792. ... },
  793. ... )
  794. <Dog: Rufus>
  795. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": None})
  796. <Dog: Meg>
  797. >>> Dog.objects.filter(data__breed="collie")
  798. <QuerySet [<Dog: Meg>]>
  799. Multiple keys can be chained together to form a path lookup:
  800. .. code-block:: pycon
  801. >>> Dog.objects.filter(data__owner__name="Bob")
  802. <QuerySet [<Dog: Rufus>]>
  803. If the key is an integer, it will be interpreted as an index transform in an
  804. array:
  805. .. code-block:: pycon
  806. >>> Dog.objects.filter(data__owner__other_pets__0__name="Fishy")
  807. <QuerySet [<Dog: Rufus>]>
  808. If the key you wish to query by clashes with the name of another lookup, use
  809. the :lookup:`contains <jsonfield.contains>` lookup instead.
  810. To query for missing keys, use the ``isnull`` lookup:
  811. .. code-block:: pycon
  812. >>> Dog.objects.create(name="Shep", data={"breed": "collie"})
  813. <Dog: Shep>
  814. >>> Dog.objects.filter(data__owner__isnull=True)
  815. <QuerySet [<Dog: Shep>]>
  816. .. note::
  817. The lookup examples given above implicitly use the :lookup:`exact` lookup.
  818. Key, index, and path transforms can also be chained with:
  819. :lookup:`icontains`, :lookup:`endswith`, :lookup:`iendswith`,
  820. :lookup:`iexact`, :lookup:`regex`, :lookup:`iregex`, :lookup:`startswith`,
  821. :lookup:`istartswith`, :lookup:`lt`, :lookup:`lte`, :lookup:`gt`, and
  822. :lookup:`gte`, as well as with :ref:`containment-and-key-lookups`.
  823. ``KT()`` expressions
  824. ~~~~~~~~~~~~~~~~~~~~
  825. .. module:: django.db.models.fields.json
  826. .. class:: KT(lookup)
  827. Represents the text value of a key, index, or path transform of
  828. :class:`~django.db.models.JSONField`. You can use the double underscore
  829. notation in ``lookup`` to chain dictionary key and index transforms.
  830. For example:
  831. .. code-block:: pycon
  832. >>> from django.db.models.fields.json import KT
  833. >>> Dog.objects.create(
  834. ... name="Shep",
  835. ... data={
  836. ... "owner": {"name": "Bob"},
  837. ... "breed": ["collie", "lhasa apso"],
  838. ... },
  839. ... )
  840. <Dog: Shep>
  841. >>> Dogs.objects.annotate(
  842. ... first_breed=KT("data__breed__1"), owner_name=KT("data__owner__name")
  843. ... ).filter(first_breed__startswith="lhasa", owner_name="Bob")
  844. <QuerySet [<Dog: Shep>]>
  845. .. note::
  846. Due to the way in which key-path queries work,
  847. :meth:`~django.db.models.query.QuerySet.exclude` and
  848. :meth:`~django.db.models.query.QuerySet.filter` are not guaranteed to
  849. produce exhaustive sets. If you want to include objects that do not have
  850. the path, add the ``isnull`` lookup.
  851. .. warning::
  852. Since any string could be a key in a JSON object, any lookup other than
  853. those listed below will be interpreted as a key lookup. No errors are
  854. raised. Be extra careful for typing mistakes, and always check your queries
  855. work as you intend.
  856. .. admonition:: MariaDB and Oracle users
  857. Using :meth:`~django.db.models.query.QuerySet.order_by` on key, index, or
  858. path transforms will sort the objects using the string representation of
  859. the values. This is because MariaDB and Oracle Database do not provide a
  860. function that converts JSON values into their equivalent SQL values.
  861. .. admonition:: Oracle users
  862. On Oracle Database, using ``None`` as the lookup value in an
  863. :meth:`~django.db.models.query.QuerySet.exclude` query will return objects
  864. that do not have ``null`` as the value at the given path, including objects
  865. that do not have the path. On other database backends, the query will
  866. return objects that have the path and the value is not ``null``.
  867. .. admonition:: PostgreSQL users
  868. On PostgreSQL, if only one key or index is used, the SQL operator ``->`` is
  869. used. If multiple operators are used then the ``#>`` operator is used.
  870. .. admonition:: SQLite users
  871. On SQLite, ``"true"``, ``"false"``, and ``"null"`` string values will
  872. always be interpreted as ``True``, ``False``, and JSON ``null``
  873. respectively.
  874. .. _containment-and-key-lookups:
  875. Containment and key lookups
  876. ---------------------------
  877. .. fieldlookup:: jsonfield.contains
  878. ``contains``
  879. ~~~~~~~~~~~~
  880. The :lookup:`contains` lookup is overridden on ``JSONField``. The returned
  881. objects are those where the given ``dict`` of key-value pairs are all
  882. contained in the top-level of the field. For example:
  883. .. code-block:: pycon
  884. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
  885. <Dog: Rufus>
  886. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  887. <Dog: Meg>
  888. >>> Dog.objects.create(name="Fred", data={})
  889. <Dog: Fred>
  890. >>> Dog.objects.filter(data__contains={"owner": "Bob"})
  891. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  892. >>> Dog.objects.filter(data__contains={"breed": "collie"})
  893. <QuerySet [<Dog: Meg>]>
  894. .. admonition:: Oracle and SQLite
  895. ``contains`` is not supported on Oracle and SQLite.
  896. .. fieldlookup:: jsonfield.contained_by
  897. ``contained_by``
  898. ~~~~~~~~~~~~~~~~
  899. This is the inverse of the :lookup:`contains <jsonfield.contains>` lookup - the
  900. objects returned will be those where the key-value pairs on the object are a
  901. subset of those in the value passed. For example:
  902. .. code-block:: pycon
  903. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
  904. <Dog: Rufus>
  905. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  906. <Dog: Meg>
  907. >>> Dog.objects.create(name="Fred", data={})
  908. <Dog: Fred>
  909. >>> Dog.objects.filter(data__contained_by={"breed": "collie", "owner": "Bob"})
  910. <QuerySet [<Dog: Meg>, <Dog: Fred>]>
  911. >>> Dog.objects.filter(data__contained_by={"breed": "collie"})
  912. <QuerySet [<Dog: Fred>]>
  913. .. admonition:: Oracle and SQLite
  914. ``contained_by`` is not supported on Oracle and SQLite.
  915. .. fieldlookup:: jsonfield.has_key
  916. ``has_key``
  917. ~~~~~~~~~~~
  918. Returns objects where the given key is in the top-level of the data. For
  919. example:
  920. .. code-block:: pycon
  921. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  922. <Dog: Rufus>
  923. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  924. <Dog: Meg>
  925. >>> Dog.objects.filter(data__has_key="owner")
  926. <QuerySet [<Dog: Meg>]>
  927. .. fieldlookup:: jsonfield.has_any_keys
  928. ``has_keys``
  929. ~~~~~~~~~~~~
  930. Returns objects where all of the given keys are in the top-level of the data.
  931. For example:
  932. .. code-block:: pycon
  933. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  934. <Dog: Rufus>
  935. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  936. <Dog: Meg>
  937. >>> Dog.objects.filter(data__has_keys=["breed", "owner"])
  938. <QuerySet [<Dog: Meg>]>
  939. .. fieldlookup:: jsonfield.has_keys
  940. ``has_any_keys``
  941. ~~~~~~~~~~~~~~~~
  942. Returns objects where any of the given keys are in the top-level of the data.
  943. For example:
  944. .. code-block:: pycon
  945. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  946. <Dog: Rufus>
  947. >>> Dog.objects.create(name="Meg", data={"owner": "Bob"})
  948. <Dog: Meg>
  949. >>> Dog.objects.filter(data__has_any_keys=["owner", "breed"])
  950. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  951. .. _complex-lookups-with-q:
  952. Complex lookups with ``Q`` objects
  953. ==================================
  954. Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
  955. etc. -- are "AND"ed together. If you need to execute more complex queries (for
  956. example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.
  957. A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object
  958. used to encapsulate a collection of keyword arguments. These keyword arguments
  959. are specified as in "Field lookups" above.
  960. For example, this ``Q`` object encapsulates a single ``LIKE`` query::
  961. from django.db.models import Q
  962. Q(question__startswith="What")
  963. ``Q`` objects can be combined using the ``&``, ``|``, and ``^`` operators. When
  964. an operator is used on two ``Q`` objects, it yields a new ``Q`` object.
  965. For example, this statement yields a single ``Q`` object that represents the
  966. "OR" of two ``"question__startswith"`` queries::
  967. Q(question__startswith="Who") | Q(question__startswith="What")
  968. This is equivalent to the following SQL ``WHERE`` clause:
  969. .. code-block:: sql
  970. WHERE question LIKE 'Who%' OR question LIKE 'What%'
  971. You can compose statements of arbitrary complexity by combining ``Q`` objects
  972. with the ``&``, ``|``, and ``^`` operators and use parenthetical grouping.
  973. Also, ``Q`` objects can be negated using the ``~`` operator, allowing for
  974. combined lookups that combine both a normal query and a negated (``NOT``)
  975. query::
  976. Q(question__startswith="Who") | ~Q(pub_date__year=2005)
  977. Each lookup function that takes keyword-arguments
  978. (e.g. :meth:`~django.db.models.query.QuerySet.filter`,
  979. :meth:`~django.db.models.query.QuerySet.exclude`,
  980. :meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more
  981. ``Q`` objects as positional (not-named) arguments. If you provide multiple
  982. ``Q`` object arguments to a lookup function, the arguments will be "AND"ed
  983. together. For example::
  984. Poll.objects.get(
  985. Q(question__startswith="Who"),
  986. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
  987. )
  988. ... roughly translates into the SQL:
  989. .. code-block:: sql
  990. SELECT * from polls WHERE question LIKE 'Who%'
  991. AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
  992. Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
  993. arguments provided to a lookup function (be they keyword arguments or ``Q``
  994. objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
  995. precede the definition of any keyword arguments. For example::
  996. Poll.objects.get(
  997. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
  998. question__startswith="Who",
  999. )
  1000. ... would be a valid query, equivalent to the previous example; but::
  1001. # INVALID QUERY
  1002. Poll.objects.get(
  1003. question__startswith="Who",
  1004. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
  1005. )
  1006. ... would not be valid.
  1007. .. seealso::
  1008. The :source:`OR lookups examples <tests/or_lookups/tests.py>` in Django's
  1009. unit tests show some possible uses of ``Q``.
  1010. Comparing objects
  1011. =================
  1012. To compare two model instances, use the standard Python comparison operator,
  1013. the double equals sign: ``==``. Behind the scenes, that compares the primary
  1014. key values of two models.
  1015. Using the ``Entry`` example above, the following two statements are equivalent:
  1016. .. code-block:: pycon
  1017. >>> some_entry == other_entry
  1018. >>> some_entry.id == other_entry.id
  1019. If a model's primary key isn't called ``id``, no problem. Comparisons will
  1020. always use the primary key, whatever it's called. For example, if a model's
  1021. primary key field is called ``name``, these two statements are equivalent:
  1022. .. code-block:: pycon
  1023. >>> some_obj == other_obj
  1024. >>> some_obj.name == other_obj.name
  1025. .. _topics-db-queries-delete:
  1026. Deleting objects
  1027. ================
  1028. The delete method, conveniently, is named
  1029. :meth:`~django.db.models.Model.delete`. This method immediately deletes the
  1030. object and returns the number of objects deleted and a dictionary with
  1031. the number of deletions per object type. Example:
  1032. .. code-block:: pycon
  1033. >>> e.delete()
  1034. (1, {'blog.Entry': 1})
  1035. You can also delete objects in bulk. Every
  1036. :class:`~django.db.models.query.QuerySet` has a
  1037. :meth:`~django.db.models.query.QuerySet.delete` method, which deletes all
  1038. members of that :class:`~django.db.models.query.QuerySet`.
  1039. For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
  1040. 2005:
  1041. .. code-block:: pycon
  1042. >>> Entry.objects.filter(pub_date__year=2005).delete()
  1043. (5, {'webapp.Entry': 5})
  1044. Keep in mind that this will, whenever possible, be executed purely in SQL, and
  1045. so the ``delete()`` methods of individual object instances will not necessarily
  1046. be called during the process. If you've provided a custom ``delete()`` method
  1047. on a model class and want to ensure that it is called, you will need to
  1048. "manually" delete instances of that model (e.g., by iterating over a
  1049. :class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each
  1050. object individually) rather than using the bulk
  1051. :meth:`~django.db.models.query.QuerySet.delete` method of a
  1052. :class:`~django.db.models.query.QuerySet`.
  1053. When Django deletes an object, by default it emulates the behavior of the SQL
  1054. constraint ``ON DELETE CASCADE`` -- in other words, any objects which had
  1055. foreign keys pointing at the object to be deleted will be deleted along with
  1056. it. For example::
  1057. b = Blog.objects.get(pk=1)
  1058. # This will delete the Blog and all of its Entry objects.
  1059. b.delete()
  1060. This cascade behavior is customizable via the
  1061. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  1062. :class:`~django.db.models.ForeignKey`.
  1063. Note that :meth:`~django.db.models.query.QuerySet.delete` is the only
  1064. :class:`~django.db.models.query.QuerySet` method that is not exposed on a
  1065. :class:`~django.db.models.Manager` itself. This is a safety mechanism to
  1066. prevent you from accidentally requesting ``Entry.objects.delete()``, and
  1067. deleting *all* the entries. If you *do* want to delete all the objects, then
  1068. you have to explicitly request a complete query set::
  1069. Entry.objects.all().delete()
  1070. .. _topics-db-queries-copy:
  1071. Copying model instances
  1072. =======================
  1073. Although there is no built-in method for copying model instances, it is
  1074. possible to easily create new instance with all fields' values copied. In the
  1075. simplest case, you can set ``pk`` to ``None`` and
  1076. :attr:`_state.adding <django.db.models.Model._state>` to ``True``. Using our
  1077. blog example::
  1078. blog = Blog(name="My blog", tagline="Blogging is easy")
  1079. blog.save() # blog.pk == 1
  1080. blog.pk = None
  1081. blog._state.adding = True
  1082. blog.save() # blog.pk == 2
  1083. Things get more complicated if you use inheritance. Consider a subclass of
  1084. ``Blog``::
  1085. class ThemeBlog(Blog):
  1086. theme = models.CharField(max_length=200)
  1087. django_blog = ThemeBlog(name="Django", tagline="Django is easy", theme="python")
  1088. django_blog.save() # django_blog.pk == 3
  1089. Due to how inheritance works, you have to set both ``pk`` and ``id`` to
  1090. ``None``, and ``_state.adding`` to ``True``::
  1091. django_blog.pk = None
  1092. django_blog.id = None
  1093. django_blog._state.adding = True
  1094. django_blog.save() # django_blog.pk == 4
  1095. This process doesn't copy relations that aren't part of the model's database
  1096. table. For example, ``Entry`` has a ``ManyToManyField`` to ``Author``. After
  1097. duplicating an entry, you must set the many-to-many relations for the new
  1098. entry::
  1099. entry = Entry.objects.all()[0] # some previous entry
  1100. old_authors = entry.authors.all()
  1101. entry.pk = None
  1102. entry._state.adding = True
  1103. entry.save()
  1104. entry.authors.set(old_authors)
  1105. For a ``OneToOneField``, you must duplicate the related object and assign it
  1106. to the new object's field to avoid violating the one-to-one unique constraint.
  1107. For example, assuming ``entry`` is already duplicated as above::
  1108. detail = EntryDetail.objects.all()[0]
  1109. detail.pk = None
  1110. detail._state.adding = True
  1111. detail.entry = entry
  1112. detail.save()
  1113. .. _topics-db-queries-update:
  1114. Updating multiple objects at once
  1115. =================================
  1116. Sometimes you want to set a field to a particular value for all the objects in
  1117. a :class:`~django.db.models.query.QuerySet`. You can do this with the
  1118. :meth:`~django.db.models.query.QuerySet.update` method. For example::
  1119. # Update all the headlines with pub_date in 2007.
  1120. Entry.objects.filter(pub_date__year=2007).update(headline="Everything is the same")
  1121. You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
  1122. fields using this method. To update a non-relation field, provide the new value
  1123. as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
  1124. new value to be the new model instance you want to point to. For example:
  1125. .. code-block:: pycon
  1126. >>> b = Blog.objects.get(pk=1)
  1127. # Change every Entry so that it belongs to this Blog.
  1128. >>> Entry.objects.update(blog=b)
  1129. The ``update()`` method is applied instantly and returns the number of rows
  1130. matched by the query (which may not be equal to the number of rows updated if
  1131. some rows already have the new value). The only restriction on the
  1132. :class:`~django.db.models.query.QuerySet` being updated is that it can only
  1133. access one database table: the model's main table. You can filter based on
  1134. related fields, but you can only update columns in the model's main
  1135. table. Example:
  1136. .. code-block:: pycon
  1137. >>> b = Blog.objects.get(pk=1)
  1138. # Update all the headlines belonging to this Blog.
  1139. >>> Entry.objects.filter(blog=b).update(headline="Everything is the same")
  1140. Be aware that the ``update()`` method is converted directly to an SQL
  1141. statement. It is a bulk operation for direct updates. It doesn't run any
  1142. :meth:`~django.db.models.Model.save` methods on your models, or emit the
  1143. ``pre_save`` or ``post_save`` signals (which are a consequence of calling
  1144. :meth:`~django.db.models.Model.save`), or honor the
  1145. :attr:`~django.db.models.DateField.auto_now` field option.
  1146. If you want to save every item in a :class:`~django.db.models.query.QuerySet`
  1147. and make sure that the :meth:`~django.db.models.Model.save` method is called on
  1148. each instance, you don't need any special function to handle that. Loop over
  1149. them and call :meth:`~django.db.models.Model.save`::
  1150. for item in my_queryset:
  1151. item.save()
  1152. Calls to update can also use :class:`F expressions <django.db.models.F>` to
  1153. update one field based on the value of another field in the model. This is
  1154. especially useful for incrementing counters based upon their current value. For
  1155. example, to increment the pingback count for every entry in the blog:
  1156. .. code-block:: pycon
  1157. >>> Entry.objects.update(number_of_pingbacks=F("number_of_pingbacks") + 1)
  1158. However, unlike ``F()`` objects in filter and exclude clauses, you can't
  1159. introduce joins when you use ``F()`` objects in an update -- you can only
  1160. reference fields local to the model being updated. If you attempt to introduce
  1161. a join with an ``F()`` object, a ``FieldError`` will be raised:
  1162. .. code-block:: pycon
  1163. # This will raise a FieldError
  1164. >>> Entry.objects.update(headline=F("blog__name"))
  1165. .. _topics-db-queries-related:
  1166. Related objects
  1167. ===============
  1168. When you define a relationship in a model (i.e., a
  1169. :class:`~django.db.models.ForeignKey`,
  1170. :class:`~django.db.models.OneToOneField`, or
  1171. :class:`~django.db.models.ManyToManyField`), instances of that model will have
  1172. a convenient API to access the related object(s).
  1173. Using the models at the top of this page, for example, an ``Entry`` object ``e``
  1174. can get its associated ``Blog`` object by accessing the ``blog`` attribute:
  1175. ``e.blog``.
  1176. (Behind the scenes, this functionality is implemented by Python
  1177. :doc:`descriptors <python:howto/descriptor>`. This shouldn't really matter to
  1178. you, but we point it out here for the curious.)
  1179. Django also creates API accessors for the "other" side of the relationship --
  1180. the link from the related model to the model that defines the relationship.
  1181. For example, a ``Blog`` object ``b`` has access to a list of all related
  1182. ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
  1183. All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
  1184. models defined at the top of this page.
  1185. One-to-many relationships
  1186. -------------------------
  1187. Forward
  1188. ~~~~~~~
  1189. If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
  1190. will have access to the related (foreign) object via an attribute of the model.
  1191. Example:
  1192. .. code-block:: pycon
  1193. >>> e = Entry.objects.get(id=2)
  1194. >>> e.blog # Returns the related Blog object.
  1195. You can get and set via a foreign-key attribute. As you may expect, changes to
  1196. the foreign key aren't saved to the database until you call
  1197. :meth:`~django.db.models.Model.save`. Example:
  1198. .. code-block:: pycon
  1199. >>> e = Entry.objects.get(id=2)
  1200. >>> e.blog = some_blog
  1201. >>> e.save()
  1202. If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,
  1203. it allows ``NULL`` values), you can assign ``None`` to remove the relation.
  1204. Example:
  1205. .. code-block:: pycon
  1206. >>> e = Entry.objects.get(id=2)
  1207. >>> e.blog = None
  1208. >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
  1209. Forward access to one-to-many relationships is cached the first time the
  1210. related object is accessed. Subsequent accesses to the foreign key on the same
  1211. object instance are cached. Example:
  1212. .. code-block:: pycon
  1213. >>> e = Entry.objects.get(id=2)
  1214. >>> print(e.blog) # Hits the database to retrieve the associated Blog.
  1215. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  1216. Note that the :meth:`~django.db.models.query.QuerySet.select_related`
  1217. :class:`~django.db.models.query.QuerySet` method recursively prepopulates the
  1218. cache of all one-to-many relationships ahead of time. Example:
  1219. .. code-block:: pycon
  1220. >>> e = Entry.objects.select_related().get(id=2)
  1221. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  1222. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  1223. .. _backwards-related-objects:
  1224. Following relationships "backward"
  1225. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1226. If a model has a :class:`~django.db.models.ForeignKey`, instances of the
  1227. foreign-key model will have access to a :class:`~django.db.models.Manager` that
  1228. returns all instances of the first model. By default, this
  1229. :class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the
  1230. source model name, lowercased. This :class:`~django.db.models.Manager` returns
  1231. ``QuerySets``, which can be filtered and manipulated as described in the
  1232. "Retrieving objects" section above.
  1233. Example:
  1234. .. code-block:: pycon
  1235. >>> b = Blog.objects.get(id=1)
  1236. >>> b.entry_set.all() # Returns all Entry objects related to Blog.
  1237. # b.entry_set is a Manager that returns QuerySets.
  1238. >>> b.entry_set.filter(headline__contains="Lennon")
  1239. >>> b.entry_set.count()
  1240. You can override the ``FOO_set`` name by setting the
  1241. :attr:`~django.db.models.ForeignKey.related_name` parameter in the
  1242. :class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``
  1243. model was altered to ``blog = ForeignKey(Blog, on_delete=models.CASCADE,
  1244. related_name='entries')``, the above example code would look like this:
  1245. .. code-block:: pycon
  1246. >>> b = Blog.objects.get(id=1)
  1247. >>> b.entries.all() # Returns all Entry objects related to Blog.
  1248. # b.entries is a Manager that returns QuerySets.
  1249. >>> b.entries.filter(headline__contains="Lennon")
  1250. >>> b.entries.count()
  1251. .. _using-custom-reverse-manager:
  1252. Using a custom reverse manager
  1253. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1254. By default the :class:`~django.db.models.fields.related.RelatedManager` used
  1255. for reverse relations is a subclass of the :ref:`default manager <manager-names>`
  1256. for that model. If you would like to specify a different manager for a given
  1257. query you can use the following syntax::
  1258. from django.db import models
  1259. class Entry(models.Model):
  1260. # ...
  1261. objects = models.Manager() # Default Manager
  1262. entries = EntryManager() # Custom Manager
  1263. b = Blog.objects.get(id=1)
  1264. b.entry_set(manager="entries").all()
  1265. If ``EntryManager`` performed default filtering in its ``get_queryset()``
  1266. method, that filtering would apply to the ``all()`` call.
  1267. Specifying a custom reverse manager also enables you to call its custom
  1268. methods::
  1269. b.entry_set(manager="entries").is_published()
  1270. .. admonition:: Interaction with prefetching
  1271. When calling :meth:`~django.db.models.query.QuerySet.prefetch_related` with
  1272. a reverse relation, the default manager will be used. If you want to
  1273. prefetch related objects using a custom reverse manager, use
  1274. :class:`Prefetch() <django.db.models.Prefetch>`. For example::
  1275. from django.db.models import Prefetch
  1276. prefetch_manager = Prefetch("entry_set", queryset=Entry.entries.all())
  1277. Blog.objects.prefetch_related(prefetch_manager)
  1278. Additional methods to handle related objects
  1279. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1280. In addition to the :class:`~django.db.models.query.QuerySet` methods defined in
  1281. "Retrieving objects" above, the :class:`~django.db.models.ForeignKey`
  1282. :class:`~django.db.models.Manager` has additional methods used to handle the
  1283. set of related objects. A synopsis of each is below, and complete details can
  1284. be found in the :doc:`related objects reference </ref/models/relations>`.
  1285. ``add(obj1, obj2, ...)``
  1286. Adds the specified model objects to the related object set.
  1287. ``create(**kwargs)``
  1288. Creates a new object, saves it and puts it in the related object set.
  1289. Returns the newly created object.
  1290. ``remove(obj1, obj2, ...)``
  1291. Removes the specified model objects from the related object set.
  1292. ``clear()``
  1293. Removes all objects from the related object set.
  1294. ``set(objs)``
  1295. Replace the set of related objects.
  1296. To assign the members of a related set, use the ``set()`` method with an
  1297. iterable of object instances. For example, if ``e1`` and ``e2`` are ``Entry``
  1298. instances::
  1299. b = Blog.objects.get(id=1)
  1300. b.entry_set.set([e1, e2])
  1301. If the ``clear()`` method is available, any preexisting objects will be
  1302. removed from the ``entry_set`` before all objects in the iterable (in this
  1303. case, a list) are added to the set. If the ``clear()`` method is *not*
  1304. available, all objects in the iterable will be added without removing any
  1305. existing elements.
  1306. Each "reverse" operation described in this section has an immediate effect on
  1307. the database. Every addition, creation and deletion is immediately and
  1308. automatically saved to the database.
  1309. .. _m2m-reverse-relationships:
  1310. Many-to-many relationships
  1311. --------------------------
  1312. Both ends of a many-to-many relationship get automatic API access to the other
  1313. end. The API works similar to a "backward" one-to-many relationship, above.
  1314. One difference is in the attribute naming: The model that defines the
  1315. :class:`~django.db.models.ManyToManyField` uses the attribute name of that
  1316. field itself, whereas the "reverse" model uses the lowercased model name of the
  1317. original model, plus ``'_set'`` (just like reverse one-to-many relationships).
  1318. An example makes this easier to understand::
  1319. e = Entry.objects.get(id=3)
  1320. e.authors.all() # Returns all Author objects for this Entry.
  1321. e.authors.count()
  1322. e.authors.filter(name__contains="John")
  1323. a = Author.objects.get(id=5)
  1324. a.entry_set.all() # Returns all Entry objects for this Author.
  1325. Like :class:`~django.db.models.ForeignKey`,
  1326. :class:`~django.db.models.ManyToManyField` can specify
  1327. :attr:`~django.db.models.ManyToManyField.related_name`. In the above example,
  1328. if the :class:`~django.db.models.ManyToManyField` in ``Entry`` had specified
  1329. ``related_name='entries'``, then each ``Author`` instance would have an
  1330. ``entries`` attribute instead of ``entry_set``.
  1331. Another difference from one-to-many relationships is that in addition to model
  1332. instances, the ``add()``, ``set()``, and ``remove()`` methods on many-to-many
  1333. relationships accept primary key values. For example, if ``e1`` and ``e2`` are
  1334. ``Entry`` instances, then these ``set()`` calls work identically::
  1335. a = Author.objects.get(id=5)
  1336. a.entry_set.set([e1, e2])
  1337. a.entry_set.set([e1.pk, e2.pk])
  1338. One-to-one relationships
  1339. ------------------------
  1340. One-to-one relationships are very similar to many-to-one relationships. If you
  1341. define a :class:`~django.db.models.OneToOneField` on your model, instances of
  1342. that model will have access to the related object via an attribute of the
  1343. model.
  1344. For example::
  1345. class EntryDetail(models.Model):
  1346. entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
  1347. details = models.TextField()
  1348. ed = EntryDetail.objects.get(id=2)
  1349. ed.entry # Returns the related Entry object.
  1350. The difference comes in "reverse" queries. The related model in a one-to-one
  1351. relationship also has access to a :class:`~django.db.models.Manager` object, but
  1352. that :class:`~django.db.models.Manager` represents a single object, rather than
  1353. a collection of objects::
  1354. e = Entry.objects.get(id=2)
  1355. e.entrydetail # returns the related EntryDetail object
  1356. If no object has been assigned to this relationship, Django will raise
  1357. a ``DoesNotExist`` exception.
  1358. Instances can be assigned to the reverse relationship in the same way as
  1359. you would assign the forward relationship::
  1360. e.entrydetail = ed
  1361. How are the backward relationships possible?
  1362. --------------------------------------------
  1363. Other object-relational mappers require you to define relationships on both
  1364. sides. The Django developers believe this is a violation of the DRY (Don't
  1365. Repeat Yourself) principle, so Django only requires you to define the
  1366. relationship on one end.
  1367. But how is this possible, given that a model class doesn't know which other
  1368. model classes are related to it until those other model classes are loaded?
  1369. The answer lies in the :data:`app registry <django.apps.apps>`. When Django
  1370. starts, it imports each application listed in :setting:`INSTALLED_APPS`, and
  1371. then the ``models`` module inside each application. Whenever a new model class
  1372. is created, Django adds backward-relationships to any related models. If the
  1373. related models haven't been imported yet, Django keeps tracks of the
  1374. relationships and adds them when the related models eventually are imported.
  1375. For this reason, it's particularly important that all the models you're using
  1376. be defined in applications listed in :setting:`INSTALLED_APPS`. Otherwise,
  1377. backwards relations may not work properly.
  1378. Queries over related objects
  1379. ----------------------------
  1380. Queries involving related objects follow the same rules as queries involving
  1381. normal value fields. When specifying the value for a query to match, you may
  1382. use either an object instance itself, or the primary key value for the object.
  1383. For example, if you have a Blog object ``b`` with ``id=5``, the following
  1384. three queries would be identical::
  1385. Entry.objects.filter(blog=b) # Query using object instance
  1386. Entry.objects.filter(blog=b.id) # Query using id from instance
  1387. Entry.objects.filter(blog=5) # Query using id directly
  1388. Falling back to raw SQL
  1389. =======================
  1390. If you find yourself needing to write an SQL query that is too complex for
  1391. Django's database-mapper to handle, you can fall back on writing SQL by hand.
  1392. Django has a couple of options for writing raw SQL queries; see
  1393. :doc:`/topics/db/sql`.
  1394. Finally, it's important to note that the Django database layer is merely an
  1395. interface to your database. You can access your database via other tools,
  1396. programming languages or database frameworks; there's nothing Django-specific
  1397. about your database.