queries.txt 71 KB

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