queries.txt 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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 Weblog application:
  12. .. _queryset-model-example:
  13. .. code-block:: python
  14. from django.db import models
  15. class Blog(models.Model):
  16. name = models.CharField(max_length=100)
  17. tagline = models.TextField()
  18. def __str__(self):
  19. return self.name
  20. class Author(models.Model):
  21. name = models.CharField(max_length=200)
  22. email = models.EmailField()
  23. def __str__(self):
  24. return self.name
  25. class Entry(models.Model):
  26. blog = models.ForeignKey(Blog)
  27. headline = models.CharField(max_length=255)
  28. body_text = models.TextField()
  29. pub_date = models.DateField()
  30. mod_date = models.DateField()
  31. authors = models.ManyToManyField(Author)
  32. n_comments = models.IntegerField()
  33. n_pingbacks = models.IntegerField()
  34. rating = models.IntegerField()
  35. def __str__(self):
  36. return self.headline
  37. Creating objects
  38. ================
  39. To represent database-table data in Python objects, Django uses an intuitive
  40. system: A model class represents a database table, and an instance of that
  41. class represents a particular record in the database table.
  42. To create an object, instantiate it using keyword arguments to the model class,
  43. then call :meth:`~django.db.models.Model.save` to save it to the database.
  44. Assuming models live in a file ``mysite/blog/models.py``, here's an example::
  45. >>> from blog.models import Blog
  46. >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
  47. >>> b.save()
  48. This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
  49. the database until you explicitly call :meth:`~django.db.models.Model.save`.
  50. The :meth:`~django.db.models.Model.save` method has no return value.
  51. .. seealso::
  52. :meth:`~django.db.models.Model.save` takes a number of advanced options not
  53. described here. See the documentation for
  54. :meth:`~django.db.models.Model.save` for complete details.
  55. To create and save an object in a single step, use the
  56. :meth:`~django.db.models.query.QuerySet.create()` method.
  57. Saving changes to objects
  58. =========================
  59. To save changes to an object that's already in the database, use
  60. :meth:`~django.db.models.Model.save`.
  61. Given a ``Blog`` instance ``b5`` that has already been saved to the database,
  62. this example changes its name and updates its record in the database::
  63. >>> b5.name = 'New name'
  64. >>> b5.save()
  65. This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
  66. the database until you explicitly call :meth:`~django.db.models.Model.save`.
  67. Saving ``ForeignKey`` and ``ManyToManyField`` fields
  68. ----------------------------------------------------
  69. Updating a :class:`~django.db.models.ForeignKey` field works exactly the same
  70. way as saving a normal field -- simply assign an object of the right type to
  71. the field in question. This example updates the ``blog`` attribute of an
  72. ``Entry`` instance ``entry``, assuming appropriate instances of ``Entry`` and
  73. ``Blog`` are already saved to the database (so we can retrieve them below)::
  74. >>> from blog.models import Blog, Entry
  75. >>> entry = Entry.objects.get(pk=1)
  76. >>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
  77. >>> entry.blog = cheese_blog
  78. >>> entry.save()
  79. Updating a :class:`~django.db.models.ManyToManyField` works a little
  80. differently -- use the
  81. :meth:`~django.db.models.fields.related.RelatedManager.add` method on the field
  82. to add a record to the relation. This example adds the ``Author`` instance
  83. ``joe`` to the ``entry`` object::
  84. >>> from blog.models import Author
  85. >>> joe = Author.objects.create(name="Joe")
  86. >>> entry.authors.add(joe)
  87. To add multiple records to a :class:`~django.db.models.ManyToManyField` in one
  88. go, include multiple arguments in the call to
  89. :meth:`~django.db.models.fields.related.RelatedManager.add`, like this::
  90. >>> john = Author.objects.create(name="John")
  91. >>> paul = Author.objects.create(name="Paul")
  92. >>> george = Author.objects.create(name="George")
  93. >>> ringo = Author.objects.create(name="Ringo")
  94. >>> entry.authors.add(john, paul, george, ringo)
  95. Django will complain if you try to assign or add an object of the wrong type.
  96. .. _retrieving-objects:
  97. Retrieving objects
  98. ==================
  99. To retrieve objects from your database, construct a
  100. :class:`~django.db.models.query.QuerySet` via a
  101. :class:`~django.db.models.Manager` on your model class.
  102. A :class:`~django.db.models.query.QuerySet` represents a collection of objects
  103. from your database. It can have zero, one or many *filters*. Filters narrow
  104. down the query results based on the given parameters. In SQL terms, a
  105. :class:`~django.db.models.query.QuerySet` equates to a ``SELECT`` statement,
  106. and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
  107. You get a :class:`~django.db.models.query.QuerySet` by using your model's
  108. :class:`~django.db.models.Manager`. Each model has at least one
  109. :class:`~django.db.models.Manager`, and it's called
  110. :attr:`~django.db.models.Model.objects` by default. Access it directly via the
  111. model class, like so::
  112. >>> Blog.objects
  113. <django.db.models.manager.Manager object at ...>
  114. >>> b = Blog(name='Foo', tagline='Bar')
  115. >>> b.objects
  116. Traceback:
  117. ...
  118. AttributeError: "Manager isn't accessible via Blog instances."
  119. .. note::
  120. ``Managers`` are accessible only via model classes, rather than from model
  121. instances, to enforce a separation between "table-level" operations and
  122. "record-level" operations.
  123. The :class:`~django.db.models.Manager` is the main source of ``QuerySets`` for
  124. a model. For example, ``Blog.objects.all()`` returns a
  125. :class:`~django.db.models.query.QuerySet` that contains all ``Blog`` objects in
  126. the database.
  127. Retrieving all objects
  128. ----------------------
  129. The simplest way to retrieve objects from a table is to get all of them. To do
  130. this, use the :meth:`~django.db.models.query.QuerySet.all` method on a
  131. :class:`~django.db.models.Manager`::
  132. >>> all_entries = Entry.objects.all()
  133. The :meth:`~django.db.models.query.QuerySet.all` method returns a
  134. :class:`~django.db.models.query.QuerySet` of all the objects in the database.
  135. Retrieving specific objects with filters
  136. ----------------------------------------
  137. The :class:`~django.db.models.query.QuerySet` returned by
  138. :meth:`~django.db.models.query.QuerySet.all` describes all objects in the
  139. database table. Usually, though, you'll need to select only a subset of the
  140. complete set of objects.
  141. To create such a subset, you refine the initial
  142. :class:`~django.db.models.query.QuerySet`, adding filter conditions. The two
  143. most common ways to refine a :class:`~django.db.models.query.QuerySet` are:
  144. ``filter(**kwargs)``
  145. Returns a new :class:`~django.db.models.query.QuerySet` containing objects
  146. that match the given lookup parameters.
  147. ``exclude(**kwargs)``
  148. Returns a new :class:`~django.db.models.query.QuerySet` containing objects
  149. that do *not* match the given lookup parameters.
  150. The lookup parameters (``**kwargs`` in the above function definitions) should
  151. be in the format described in `Field lookups`_ below.
  152. For example, to get a :class:`~django.db.models.query.QuerySet` of blog entries
  153. from the year 2006, use :meth:`~django.db.models.query.QuerySet.filter` like
  154. so::
  155. Entry.objects.filter(pub_date__year=2006)
  156. With the default manager class, it is the same as::
  157. Entry.objects.all().filter(pub_date__year=2006)
  158. .. _chaining-filters:
  159. Chaining filters
  160. ~~~~~~~~~~~~~~~~
  161. The result of refining a :class:`~django.db.models.query.QuerySet` is itself a
  162. :class:`~django.db.models.query.QuerySet`, so it's possible to chain
  163. refinements together. For example::
  164. >>> Entry.objects.filter(
  165. ... headline__startswith='What'
  166. ... ).exclude(
  167. ... pub_date__gte=datetime.date.today()
  168. ... ).filter(
  169. ... pub_date__gte=datetime(2005, 1, 30)
  170. ... )
  171. This takes the initial :class:`~django.db.models.query.QuerySet` of all entries
  172. in the database, adds a filter, then an exclusion, then another filter. The
  173. final result is a :class:`~django.db.models.query.QuerySet` containing all
  174. entries with a headline that starts with "What", that were published between
  175. January 30, 2005, and the current day.
  176. .. _filtered-querysets-are-unique:
  177. Filtered ``QuerySet``\s are unique
  178. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  179. Each time you refine a :class:`~django.db.models.query.QuerySet`, you get a
  180. brand-new :class:`~django.db.models.query.QuerySet` that is in no way bound to
  181. the previous :class:`~django.db.models.query.QuerySet`. Each refinement creates
  182. a separate and distinct :class:`~django.db.models.query.QuerySet` that can be
  183. stored, used and reused.
  184. Example::
  185. >>> q1 = Entry.objects.filter(headline__startswith="What")
  186. >>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
  187. >>> q3 = q1.filter(pub_date__gte=datetime.date.today())
  188. These three ``QuerySets`` are separate. The first is a base
  189. :class:`~django.db.models.query.QuerySet` containing all entries that contain a
  190. headline starting with "What". The second is a subset of the first, with an
  191. additional criteria that excludes records whose ``pub_date`` is today or in the
  192. future. The third is a subset of the first, with an additional criteria that
  193. selects only the records whose ``pub_date`` is today or in the future. The
  194. initial :class:`~django.db.models.query.QuerySet` (``q1``) is unaffected by the
  195. refinement process.
  196. .. _querysets-are-lazy:
  197. ``QuerySet``\s are lazy
  198. ~~~~~~~~~~~~~~~~~~~~~~~
  199. ``QuerySets`` are lazy -- the act of creating a
  200. :class:`~django.db.models.query.QuerySet` doesn't involve any database
  201. activity. You can stack filters together all day long, and Django won't
  202. actually run the query until the :class:`~django.db.models.query.QuerySet` is
  203. *evaluated*. Take a look at this example::
  204. >>> q = Entry.objects.filter(headline__startswith="What")
  205. >>> q = q.filter(pub_date__lte=datetime.date.today())
  206. >>> q = q.exclude(body_text__icontains="food")
  207. >>> print(q)
  208. Though this looks like three database hits, in fact it hits the database only
  209. once, at the last line (``print(q)``). In general, the results of a
  210. :class:`~django.db.models.query.QuerySet` aren't fetched from the database
  211. until you "ask" for them. When you do, the
  212. :class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the
  213. database. For more details on exactly when evaluation takes place, see
  214. :ref:`when-querysets-are-evaluated`.
  215. .. _retrieving-single-object-with-get:
  216. Retrieving a single object with ``get()``
  217. -----------------------------------------
  218. :meth:`~django.db.models.query.QuerySet.filter` will always give you a
  219. :class:`~django.db.models.query.QuerySet`, even if only a single object matches
  220. the query - in this case, it will be a
  221. :class:`~django.db.models.query.QuerySet` containing a single element.
  222. If you know there is only one object that matches your query, you can use the
  223. :meth:`~django.db.models.query.QuerySet.get` method on a
  224. :class:`~django.db.models.Manager` which returns the object directly::
  225. >>> one_entry = Entry.objects.get(pk=1)
  226. You can use any query expression with
  227. :meth:`~django.db.models.query.QuerySet.get`, just like with
  228. :meth:`~django.db.models.query.QuerySet.filter` - again, see `Field lookups`_
  229. below.
  230. Note that there is a difference between using
  231. :meth:`~django.db.models.query.QuerySet.get`, and using
  232. :meth:`~django.db.models.query.QuerySet.filter` with a slice of ``[0]``. If
  233. there are no results that match the query,
  234. :meth:`~django.db.models.query.QuerySet.get` will raise a ``DoesNotExist``
  235. exception. This exception is an attribute of the model class that the query is
  236. being performed on - so in the code above, if there is no ``Entry`` object with
  237. a primary key of 1, Django will raise ``Entry.DoesNotExist``.
  238. Similarly, Django will complain if more than one item matches the
  239. :meth:`~django.db.models.query.QuerySet.get` query. In this case, it will raise
  240. :exc:`~django.core.exceptions.MultipleObjectsReturned`, which again is an
  241. attribute of the model class itself.
  242. Other ``QuerySet`` methods
  243. --------------------------
  244. Most of the time you'll use :meth:`~django.db.models.query.QuerySet.all`,
  245. :meth:`~django.db.models.query.QuerySet.get`,
  246. :meth:`~django.db.models.query.QuerySet.filter` and
  247. :meth:`~django.db.models.query.QuerySet.exclude` when you need to look up
  248. objects from the database. However, that's far from all there is; see the
  249. :ref:`QuerySet API Reference <queryset-api>` for a complete list of all the
  250. various :class:`~django.db.models.query.QuerySet` methods.
  251. .. _limiting-querysets:
  252. Limiting ``QuerySet``\s
  253. -----------------------
  254. Use a subset of Python's array-slicing syntax to limit your
  255. :class:`~django.db.models.query.QuerySet` to a certain number of results. This
  256. is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
  257. For example, this returns the first 5 objects (``LIMIT 5``)::
  258. >>> Entry.objects.all()[:5]
  259. This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
  260. >>> Entry.objects.all()[5:10]
  261. Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported.
  262. Generally, slicing a :class:`~django.db.models.query.QuerySet` returns a new
  263. :class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An
  264. exception is if you use the "step" parameter of Python slice syntax. For
  265. example, this would actually execute the query in order to return a list of
  266. every *second* object of the first 10::
  267. >>> Entry.objects.all()[:10:2]
  268. Further filtering or ordering of a sliced queryset is prohibited due to the
  269. ambiguous nature of how that might work.
  270. To retrieve a *single* object rather than a list
  271. (e.g. ``SELECT foo FROM bar LIMIT 1``), use a simple index instead of a
  272. slice. For example, this returns the first ``Entry`` in the database, after
  273. ordering entries alphabetically by headline::
  274. >>> Entry.objects.order_by('headline')[0]
  275. This is roughly equivalent to::
  276. >>> Entry.objects.order_by('headline')[0:1].get()
  277. Note, however, that the first of these will raise ``IndexError`` while the
  278. second will raise ``DoesNotExist`` if no objects match the given criteria. See
  279. :meth:`~django.db.models.query.QuerySet.get` for more details.
  280. .. _field-lookups-intro:
  281. Field lookups
  282. -------------
  283. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
  284. specified as keyword arguments to the :class:`~django.db.models.query.QuerySet`
  285. methods :meth:`~django.db.models.query.QuerySet.filter`,
  286. :meth:`~django.db.models.query.QuerySet.exclude` and
  287. :meth:`~django.db.models.query.QuerySet.get`.
  288. Basic lookups keyword arguments take the form ``field__lookuptype=value``.
  289. (That's a double-underscore). For example::
  290. >>> Entry.objects.filter(pub_date__lte='2006-01-01')
  291. translates (roughly) into the following SQL:
  292. .. code-block:: sql
  293. SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
  294. .. admonition:: How this is possible
  295. Python has the ability to define functions that accept arbitrary name-value
  296. arguments whose names and values are evaluated at runtime. For more
  297. information, see :ref:`tut-keywordargs` in the official Python tutorial.
  298. The field specified in a lookup has to be the name of a model field. There's
  299. one exception though, in case of a :class:`~django.db.models.ForeignKey` you
  300. can specify the field name suffixed with ``_id``. In this case, the value
  301. parameter is expected to contain the raw value of the foreign model's primary
  302. key. For example:
  303. >>> Entry.objects.filter(blog_id=4)
  304. If you pass an invalid keyword argument, a lookup function will raise
  305. ``TypeError``.
  306. The database API supports about two dozen lookup types; a complete reference
  307. can be found in the :ref:`field lookup reference <field-lookups>`. To give you
  308. a taste of what's available, here's some of the more common lookups you'll
  309. probably use:
  310. :lookup:`exact`
  311. An "exact" match. For example::
  312. >>> Entry.objects.get(headline__exact="Cat bites dog")
  313. Would generate SQL along these lines:
  314. .. code-block:: sql
  315. SELECT ... WHERE headline = 'Cat bites dog';
  316. If you don't provide a lookup type -- that is, if your keyword argument
  317. doesn't contain a double underscore -- the lookup type is assumed to be
  318. ``exact``.
  319. For example, the following two statements are equivalent::
  320. >>> Blog.objects.get(id__exact=14) # Explicit form
  321. >>> Blog.objects.get(id=14) # __exact is implied
  322. This is for convenience, because ``exact`` lookups are the common case.
  323. :lookup:`iexact`
  324. A case-insensitive match. So, the query::
  325. >>> Blog.objects.get(name__iexact="beatles blog")
  326. Would match a ``Blog`` titled ``"Beatles Blog"``, ``"beatles blog"``, or
  327. even ``"BeAtlES blOG"``.
  328. :lookup:`contains`
  329. Case-sensitive containment test. For example::
  330. Entry.objects.get(headline__contains='Lennon')
  331. Roughly translates to this SQL:
  332. .. code-block:: sql
  333. SELECT ... WHERE headline LIKE '%Lennon%';
  334. Note this will match the headline ``'Today Lennon honored'`` but not
  335. ``'today lennon honored'``.
  336. There's also a case-insensitive version, :lookup:`icontains`.
  337. :lookup:`startswith`, :lookup:`endswith`
  338. Starts-with and ends-with search, respectively. There are also
  339. case-insensitive versions called :lookup:`istartswith` and
  340. :lookup:`iendswith`.
  341. Again, this only scratches the surface. A complete reference can be found in the
  342. :ref:`field lookup reference <field-lookups>`.
  343. .. _lookups-that-span-relationships:
  344. Lookups that span relationships
  345. -------------------------------
  346. Django offers a powerful and intuitive way to "follow" relationships in
  347. lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
  348. scenes. To span a relationship, just use the field name of related fields
  349. across models, separated by double underscores, until you get to the field you
  350. want.
  351. This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
  352. is ``'Beatles Blog'``::
  353. >>> Entry.objects.filter(blog__name='Beatles Blog')
  354. This spanning can be as deep as you'd like.
  355. It works backwards, too. To refer to a "reverse" relationship, just use the
  356. lowercase name of the model.
  357. This example retrieves all ``Blog`` objects which have at least one ``Entry``
  358. whose ``headline`` contains ``'Lennon'``::
  359. >>> Blog.objects.filter(entry__headline__contains='Lennon')
  360. If you are filtering across multiple relationships and one of the intermediate
  361. models doesn't have a value that meets the filter condition, Django will treat
  362. it as if there is an empty (all values are ``NULL``), but valid, object there.
  363. All this means is that no error will be raised. For example, in this filter::
  364. Blog.objects.filter(entry__authors__name='Lennon')
  365. (if there was a related ``Author`` model), if there was no ``author``
  366. associated with an entry, it would be treated as if there was also no ``name``
  367. attached, rather than raising an error because of the missing ``author``.
  368. Usually this is exactly what you want to have happen. The only case where it
  369. might be confusing is if you are using :lookup:`isnull`. Thus::
  370. Blog.objects.filter(entry__authors__name__isnull=True)
  371. will return ``Blog`` objects that have an empty ``name`` on the ``author`` and
  372. also those which have an empty ``author`` on the ``entry``. If you don't want
  373. those latter objects, you could write::
  374. Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
  375. Spanning multi-valued relationships
  376. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  377. When you are filtering an object based on a
  378. :class:`~django.db.models.ManyToManyField` or a reverse
  379. :class:`~django.db.models.ForeignKey`, there are two different sorts of filter
  380. you may be interested in. Consider the ``Blog``/``Entry`` relationship
  381. (``Blog`` to ``Entry`` is a one-to-many relation). We might be interested in
  382. finding blogs that have an entry which has both *"Lennon"* in the headline and
  383. was published in 2008. Or we might want to find blogs that have an entry with
  384. *"Lennon"* in the headline as well as an entry that was published
  385. in 2008. Since there are multiple entries associated with a single ``Blog``,
  386. both of these queries are possible and make sense in some situations.
  387. The same type of situation arises with a
  388. :class:`~django.db.models.ManyToManyField`. For example, if an ``Entry`` has a
  389. :class:`~django.db.models.ManyToManyField` called ``tags``, we might want to
  390. find entries linked to tags called *"music"* and *"bands"* or we might want an
  391. entry that contains a tag with a name of *"music"* and a status of *"public"*.
  392. To handle both of these situations, Django has a consistent way of processing
  393. :meth:`~django.db.models.query.QuerySet.filter` calls. Everything inside a
  394. single :meth:`~django.db.models.query.QuerySet.filter` call is applied
  395. simultaneously to filter out items matching all those requirements. Successive
  396. :meth:`~django.db.models.query.QuerySet.filter` calls further restrict the set
  397. of objects, but for multi-valued relations, they apply to any object linked to
  398. the primary model, not necessarily those objects that were selected by an
  399. earlier :meth:`~django.db.models.query.QuerySet.filter` call.
  400. That may sound a bit confusing, so hopefully an example will clarify. To
  401. select all blogs that contain entries with both *"Lennon"* in the headline
  402. and that were published in 2008 (the same entry satisfying both conditions),
  403. we would write::
  404. Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
  405. To select all blogs that contain an entry with *"Lennon"* in the headline
  406. **as well as** an entry that was published in 2008, we would write::
  407. Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
  408. Suppose there is only one blog that had both entries containing *"Lennon"* and
  409. entries from 2008, but that none of the entries from 2008 contained *"Lennon"*.
  410. The first query would not return any blogs, but the second query would return
  411. that one blog.
  412. In the second example, the first filter restricts the queryset to all those
  413. blogs linked to entries with *"Lennon"* in the headline. The second filter
  414. restricts the set of blogs *further* to those that are also linked to entries
  415. that were published in 2008. The entries selected by the second filter may or
  416. may not be the same as the entries in the first filter. We are filtering the
  417. ``Blog`` items with each filter statement, not the ``Entry`` items.
  418. .. note::
  419. The behavior of :meth:`~django.db.models.query.QuerySet.filter` for queries
  420. that span multi-value relationships, as described above, is not implemented
  421. equivalently for :meth:`~django.db.models.query.QuerySet.exclude`. Instead,
  422. the conditions in a single :meth:`~django.db.models.query.QuerySet.exclude`
  423. call will not necessarily refer to the same item.
  424. For example, the following query would exclude blogs that contain *both*
  425. entries with *"Lennon"* in the headline *and* entries published in 2008::
  426. Blog.objects.exclude(
  427. entry__headline__contains='Lennon',
  428. entry__pub_date__year=2008,
  429. )
  430. However, unlike the behavior when using
  431. :meth:`~django.db.models.query.QuerySet.filter`, this will not limit blogs
  432. based on entries that satisfy both conditions. In order to do that, i.e.
  433. to select all blogs that do not contain entries published with *"Lennon"*
  434. that were published in 2008, you need to make two queries::
  435. Blog.objects.exclude(
  436. entry__in=Entry.objects.filter(
  437. headline__contains='Lennon',
  438. pub_date__year=2008,
  439. ),
  440. )
  441. .. _using-f-expressions-in-filters:
  442. Filters can reference fields on the model
  443. -----------------------------------------
  444. In the examples given so far, we have constructed filters that compare
  445. the value of a model field with a constant. But what if you want to compare
  446. the value of a model field with another field on the same model?
  447. Django provides :class:`F expressions <django.db.models.F>` to allow such
  448. comparisons. Instances of ``F()`` act as a reference to a model field within a
  449. query. These references can then be used in query filters to compare the values
  450. of two different fields on the same model instance.
  451. For example, to find a list of all blog entries that have had more comments
  452. than pingbacks, we construct an ``F()`` object to reference the pingback count,
  453. and use that ``F()`` object in the query::
  454. >>> from django.db.models import F
  455. >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
  456. Django supports the use of addition, subtraction, multiplication,
  457. division, modulo, and power arithmetic with ``F()`` objects, both with constants
  458. and with other ``F()`` objects. To find all the blog entries with more than
  459. *twice* as many comments as pingbacks, we modify the query::
  460. >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)
  461. To find all the entries where the rating of the entry is less than the
  462. sum of the pingback count and comment count, we would issue the
  463. query::
  464. >>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
  465. You can also use the double underscore notation to span relationships in
  466. an ``F()`` object. An ``F()`` object with a double underscore will introduce
  467. any joins needed to access the related object. For example, to retrieve all
  468. the entries where the author's name is the same as the blog name, we could
  469. issue the query::
  470. >>> Entry.objects.filter(authors__name=F('blog__name'))
  471. For date and date/time fields, you can add or subtract a
  472. :class:`~datetime.timedelta` object. The following would return all entries
  473. that were modified more than 3 days after they were published::
  474. >>> from datetime import timedelta
  475. >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
  476. The ``F()`` objects support bitwise operations by ``.bitand()``, ``.bitor()``,
  477. ``.bitrightshift()``, and ``.bitleftshift()``. For example::
  478. >>> F('somefield').bitand(16)
  479. .. versionchanged:: 1.11
  480. Support for ``.bitrightshift()`` and ``.bitleftshift()`` was added.
  481. The ``pk`` lookup shortcut
  482. --------------------------
  483. For convenience, Django provides a ``pk`` lookup shortcut, which stands for
  484. "primary key".
  485. In the example ``Blog`` model, the primary key is the ``id`` field, so these
  486. three statements are equivalent::
  487. >>> Blog.objects.get(id__exact=14) # Explicit form
  488. >>> Blog.objects.get(id=14) # __exact is implied
  489. >>> Blog.objects.get(pk=14) # pk implies id__exact
  490. The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
  491. can be combined with ``pk`` to perform a query on the primary key of a model::
  492. # Get blogs entries with id 1, 4 and 7
  493. >>> Blog.objects.filter(pk__in=[1,4,7])
  494. # Get all blog entries with id > 14
  495. >>> Blog.objects.filter(pk__gt=14)
  496. ``pk`` lookups also work across joins. For example, these three statements are
  497. equivalent::
  498. >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
  499. >>> Entry.objects.filter(blog__id=3) # __exact is implied
  500. >>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
  501. Escaping percent signs and underscores in ``LIKE`` statements
  502. -------------------------------------------------------------
  503. The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
  504. ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
  505. and ``iendswith``) will automatically escape the two special characters used in
  506. ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
  507. statement, the percent sign signifies a multiple-character wildcard and the
  508. underscore signifies a single-character wildcard.)
  509. This means things should work intuitively, so the abstraction doesn't leak.
  510. For example, to retrieve all the entries that contain a percent sign, just use
  511. the percent sign as any other character::
  512. >>> Entry.objects.filter(headline__contains='%')
  513. Django takes care of the quoting for you; the resulting SQL will look something
  514. like this:
  515. .. code-block:: sql
  516. SELECT ... WHERE headline LIKE '%\%%';
  517. Same goes for underscores. Both percentage signs and underscores are handled
  518. for you transparently.
  519. .. _caching-and-querysets:
  520. Caching and ``QuerySet``\s
  521. --------------------------
  522. Each :class:`~django.db.models.query.QuerySet` contains a cache to minimize
  523. database access. Understanding how it works will allow you to write the most
  524. efficient code.
  525. In a newly created :class:`~django.db.models.query.QuerySet`, the cache is
  526. empty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated
  527. -- and, hence, a database query happens -- Django saves the query results in
  528. the :class:`~django.db.models.query.QuerySet`’s cache and returns the results
  529. that have been explicitly requested (e.g., the next element, if the
  530. :class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent
  531. evaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached
  532. results.
  533. Keep this caching behavior in mind, because it may bite you if you don't use
  534. your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
  535. following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
  536. them, and throw them away::
  537. >>> print([e.headline for e in Entry.objects.all()])
  538. >>> print([e.pub_date for e in Entry.objects.all()])
  539. That means the same database query will be executed twice, effectively doubling
  540. your database load. Also, there's a possibility the two lists may not include
  541. the same database records, because an ``Entry`` may have been added or deleted
  542. in the split second between the two requests.
  543. To avoid this problem, simply save the
  544. :class:`~django.db.models.query.QuerySet` and reuse it::
  545. >>> queryset = Entry.objects.all()
  546. >>> print([p.headline for p in queryset]) # Evaluate the query set.
  547. >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
  548. When ``QuerySet``\s are not cached
  549. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  550. Querysets do not always cache their results. When evaluating only *part* of
  551. the queryset, the cache is checked, but if it is not populated then the items
  552. returned by the subsequent query are not cached. Specifically, this means that
  553. :ref:`limiting the queryset <limiting-querysets>` using an array slice or an
  554. index will not populate the cache.
  555. For example, repeatedly getting a certain index in a queryset object will query
  556. the database each time::
  557. >>> queryset = Entry.objects.all()
  558. >>> print(queryset[5]) # Queries the database
  559. >>> print(queryset[5]) # Queries the database again
  560. However, if the entire queryset has already been evaluated, the cache will be
  561. checked instead::
  562. >>> queryset = Entry.objects.all()
  563. >>> [entry for entry in queryset] # Queries the database
  564. >>> print(queryset[5]) # Uses cache
  565. >>> print(queryset[5]) # Uses cache
  566. Here are some examples of other actions that will result in the entire queryset
  567. being evaluated and therefore populate the cache::
  568. >>> [entry for entry in queryset]
  569. >>> bool(queryset)
  570. >>> entry in queryset
  571. >>> list(queryset)
  572. .. note::
  573. Simply printing the queryset will not populate the cache. This is because
  574. the call to ``__repr__()`` only returns a slice of the entire queryset.
  575. .. _complex-lookups-with-q:
  576. Complex lookups with ``Q`` objects
  577. ==================================
  578. Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
  579. etc. -- are "AND"ed together. If you need to execute more complex queries (for
  580. example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.
  581. A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object
  582. used to encapsulate a collection of keyword arguments. These keyword arguments
  583. are specified as in "Field lookups" above.
  584. For example, this ``Q`` object encapsulates a single ``LIKE`` query::
  585. from django.db.models import Q
  586. Q(question__startswith='What')
  587. ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
  588. operator is used on two ``Q`` objects, it yields a new ``Q`` object.
  589. For example, this statement yields a single ``Q`` object that represents the
  590. "OR" of two ``"question__startswith"`` queries::
  591. Q(question__startswith='Who') | Q(question__startswith='What')
  592. This is equivalent to the following SQL ``WHERE`` clause::
  593. WHERE question LIKE 'Who%' OR question LIKE 'What%'
  594. You can compose statements of arbitrary complexity by combining ``Q`` objects
  595. with the ``&`` and ``|`` operators and use parenthetical grouping. Also, ``Q``
  596. objects can be negated using the ``~`` operator, allowing for combined lookups
  597. that combine both a normal query and a negated (``NOT``) query::
  598. Q(question__startswith='Who') | ~Q(pub_date__year=2005)
  599. Each lookup function that takes keyword-arguments
  600. (e.g. :meth:`~django.db.models.query.QuerySet.filter`,
  601. :meth:`~django.db.models.query.QuerySet.exclude`,
  602. :meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more
  603. ``Q`` objects as positional (not-named) arguments. If you provide multiple
  604. ``Q`` object arguments to a lookup function, the arguments will be "AND"ed
  605. together. For example::
  606. Poll.objects.get(
  607. Q(question__startswith='Who'),
  608. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
  609. )
  610. ... roughly translates into the SQL::
  611. SELECT * from polls WHERE question LIKE 'Who%'
  612. AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
  613. Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
  614. arguments provided to a lookup function (be they keyword arguments or ``Q``
  615. objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
  616. precede the definition of any keyword arguments. For example::
  617. Poll.objects.get(
  618. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
  619. question__startswith='Who',
  620. )
  621. ... would be a valid query, equivalent to the previous example; but::
  622. # INVALID QUERY
  623. Poll.objects.get(
  624. question__startswith='Who',
  625. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
  626. )
  627. ... would not be valid.
  628. .. seealso::
  629. The `OR lookups examples`_ in the Django unit tests show some possible uses
  630. of ``Q``.
  631. .. _OR lookups examples: https://github.com/django/django/blob/master/tests/or_lookups/tests.py
  632. Comparing objects
  633. =================
  634. To compare two model instances, just use the standard Python comparison operator,
  635. the double equals sign: ``==``. Behind the scenes, that compares the primary
  636. key values of two models.
  637. Using the ``Entry`` example above, the following two statements are equivalent::
  638. >>> some_entry == other_entry
  639. >>> some_entry.id == other_entry.id
  640. If a model's primary key isn't called ``id``, no problem. Comparisons will
  641. always use the primary key, whatever it's called. For example, if a model's
  642. primary key field is called ``name``, these two statements are equivalent::
  643. >>> some_obj == other_obj
  644. >>> some_obj.name == other_obj.name
  645. .. _topics-db-queries-delete:
  646. Deleting objects
  647. ================
  648. The delete method, conveniently, is named
  649. :meth:`~django.db.models.Model.delete`. This method immediately deletes the
  650. object and returns the number of objects deleted and a dictionary with
  651. the number of deletions per object type. Example::
  652. >>> e.delete()
  653. (1, {'weblog.Entry': 1})
  654. You can also delete objects in bulk. Every
  655. :class:`~django.db.models.query.QuerySet` has a
  656. :meth:`~django.db.models.query.QuerySet.delete` method, which deletes all
  657. members of that :class:`~django.db.models.query.QuerySet`.
  658. For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
  659. 2005::
  660. >>> Entry.objects.filter(pub_date__year=2005).delete()
  661. (5, {'webapp.Entry': 5})
  662. Keep in mind that this will, whenever possible, be executed purely in SQL, and
  663. so the ``delete()`` methods of individual object instances will not necessarily
  664. be called during the process. If you've provided a custom ``delete()`` method
  665. on a model class and want to ensure that it is called, you will need to
  666. "manually" delete instances of that model (e.g., by iterating over a
  667. :class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each
  668. object individually) rather than using the bulk
  669. :meth:`~django.db.models.query.QuerySet.delete` method of a
  670. :class:`~django.db.models.query.QuerySet`.
  671. When Django deletes an object, by default it emulates the behavior of the SQL
  672. constraint ``ON DELETE CASCADE`` -- in other words, any objects which had
  673. foreign keys pointing at the object to be deleted will be deleted along with
  674. it. For example::
  675. b = Blog.objects.get(pk=1)
  676. # This will delete the Blog and all of its Entry objects.
  677. b.delete()
  678. This cascade behavior is customizable via the
  679. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  680. :class:`~django.db.models.ForeignKey`.
  681. Note that :meth:`~django.db.models.query.QuerySet.delete` is the only
  682. :class:`~django.db.models.query.QuerySet` method that is not exposed on a
  683. :class:`~django.db.models.Manager` itself. This is a safety mechanism to
  684. prevent you from accidentally requesting ``Entry.objects.delete()``, and
  685. deleting *all* the entries. If you *do* want to delete all the objects, then
  686. you have to explicitly request a complete query set::
  687. Entry.objects.all().delete()
  688. .. _topics-db-queries-copy:
  689. Copying model instances
  690. =======================
  691. Although there is no built-in method for copying model instances, it is
  692. possible to easily create new instance with all fields' values copied. In the
  693. simplest case, you can just set ``pk`` to ``None``. Using our blog example::
  694. blog = Blog(name='My blog', tagline='Blogging is easy')
  695. blog.save() # blog.pk == 1
  696. blog.pk = None
  697. blog.save() # blog.pk == 2
  698. Things get more complicated if you use inheritance. Consider a subclass of
  699. ``Blog``::
  700. class ThemeBlog(Blog):
  701. theme = models.CharField(max_length=200)
  702. django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')
  703. django_blog.save() # django_blog.pk == 3
  704. Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::
  705. django_blog.pk = None
  706. django_blog.id = None
  707. django_blog.save() # django_blog.pk == 4
  708. This process doesn't copy relations that aren't part of the model's database
  709. table. For example, ``Entry`` has a ``ManyToManyField`` to ``Author``. After
  710. duplicating an entry, you must set the many-to-many relations for the new
  711. entry::
  712. entry = Entry.objects.all()[0] # some previous entry
  713. old_authors = entry.authors.all()
  714. entry.pk = None
  715. entry.save()
  716. entry.authors.set(old_authors)
  717. For a ``OneToOneField``, you must duplicate the related object and assign it
  718. to the new object's field to avoid violating the one-to-one unique constraint.
  719. For example, assuming ``entry`` is already duplicated as above::
  720. detail = EntryDetail.objects.all()[0]
  721. detail.pk = None
  722. detail.entry = entry
  723. detail.save()
  724. .. _topics-db-queries-update:
  725. Updating multiple objects at once
  726. =================================
  727. Sometimes you want to set a field to a particular value for all the objects in
  728. a :class:`~django.db.models.query.QuerySet`. You can do this with the
  729. :meth:`~django.db.models.query.QuerySet.update` method. For example::
  730. # Update all the headlines with pub_date in 2007.
  731. Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
  732. You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
  733. fields using this method. To update a non-relation field, provide the new value
  734. as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
  735. new value to be the new model instance you want to point to. For example::
  736. >>> b = Blog.objects.get(pk=1)
  737. # Change every Entry so that it belongs to this Blog.
  738. >>> Entry.objects.all().update(blog=b)
  739. The ``update()`` method is applied instantly and returns the number of rows
  740. matched by the query (which may not be equal to the number of rows updated if
  741. some rows already have the new value). The only restriction on the
  742. :class:`~django.db.models.query.QuerySet` being updated is that it can only
  743. access one database table: the model's main table. You can filter based on
  744. related fields, but you can only update columns in the model's main
  745. table. Example::
  746. >>> b = Blog.objects.get(pk=1)
  747. # Update all the headlines belonging to this Blog.
  748. >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
  749. Be aware that the ``update()`` method is converted directly to an SQL
  750. statement. It is a bulk operation for direct updates. It doesn't run any
  751. :meth:`~django.db.models.Model.save` methods on your models, or emit the
  752. ``pre_save`` or ``post_save`` signals (which are a consequence of calling
  753. :meth:`~django.db.models.Model.save`), or honor the
  754. :attr:`~django.db.models.DateField.auto_now` field option.
  755. If you want to save every item in a :class:`~django.db.models.query.QuerySet`
  756. and make sure that the :meth:`~django.db.models.Model.save` method is called on
  757. each instance, you don't need any special function to handle that. Just loop
  758. over them and call :meth:`~django.db.models.Model.save`::
  759. for item in my_queryset:
  760. item.save()
  761. Calls to update can also use :class:`F expressions <django.db.models.F>` to
  762. update one field based on the value of another field in the model. This is
  763. especially useful for incrementing counters based upon their current value. For
  764. example, to increment the pingback count for every entry in the blog::
  765. >>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
  766. However, unlike ``F()`` objects in filter and exclude clauses, you can't
  767. introduce joins when you use ``F()`` objects in an update -- you can only
  768. reference fields local to the model being updated. If you attempt to introduce
  769. a join with an ``F()`` object, a ``FieldError`` will be raised::
  770. # This will raise a FieldError
  771. >>> Entry.objects.update(headline=F('blog__name'))
  772. .. _topics-db-queries-related:
  773. Related objects
  774. ===============
  775. When you define a relationship in a model (i.e., a
  776. :class:`~django.db.models.ForeignKey`,
  777. :class:`~django.db.models.OneToOneField`, or
  778. :class:`~django.db.models.ManyToManyField`), instances of that model will have
  779. a convenient API to access the related object(s).
  780. Using the models at the top of this page, for example, an ``Entry`` object ``e``
  781. can get its associated ``Blog`` object by accessing the ``blog`` attribute:
  782. ``e.blog``.
  783. (Behind the scenes, this functionality is implemented by Python descriptors_.
  784. This shouldn't really matter to you, but we point it out here for the curious.)
  785. Django also creates API accessors for the "other" side of the relationship --
  786. the link from the related model to the model that defines the relationship.
  787. For example, a ``Blog`` object ``b`` has access to a list of all related
  788. ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
  789. All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
  790. models defined at the top of this page.
  791. .. _descriptors: https://docs.python.org/3/howto/descriptor.html
  792. One-to-many relationships
  793. -------------------------
  794. Forward
  795. ~~~~~~~
  796. If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
  797. will have access to the related (foreign) object via a simple attribute of the
  798. model.
  799. Example::
  800. >>> e = Entry.objects.get(id=2)
  801. >>> e.blog # Returns the related Blog object.
  802. You can get and set via a foreign-key attribute. As you may expect, changes to
  803. the foreign key aren't saved to the database until you call
  804. :meth:`~django.db.models.Model.save`. Example::
  805. >>> e = Entry.objects.get(id=2)
  806. >>> e.blog = some_blog
  807. >>> e.save()
  808. If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,
  809. it allows ``NULL`` values), you can assign ``None`` to remove the relation.
  810. Example::
  811. >>> e = Entry.objects.get(id=2)
  812. >>> e.blog = None
  813. >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
  814. Forward access to one-to-many relationships is cached the first time the
  815. related object is accessed. Subsequent accesses to the foreign key on the same
  816. object instance are cached. Example::
  817. >>> e = Entry.objects.get(id=2)
  818. >>> print(e.blog) # Hits the database to retrieve the associated Blog.
  819. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  820. Note that the :meth:`~django.db.models.query.QuerySet.select_related`
  821. :class:`~django.db.models.query.QuerySet` method recursively prepopulates the
  822. cache of all one-to-many relationships ahead of time. Example::
  823. >>> e = Entry.objects.select_related().get(id=2)
  824. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  825. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  826. .. _backwards-related-objects:
  827. Following relationships "backward"
  828. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  829. If a model has a :class:`~django.db.models.ForeignKey`, instances of the
  830. foreign-key model will have access to a :class:`~django.db.models.Manager` that
  831. returns all instances of the first model. By default, this
  832. :class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the
  833. source model name, lowercased. This :class:`~django.db.models.Manager` returns
  834. ``QuerySets``, which can be filtered and manipulated as described in the
  835. "Retrieving objects" section above.
  836. Example::
  837. >>> b = Blog.objects.get(id=1)
  838. >>> b.entry_set.all() # Returns all Entry objects related to Blog.
  839. # b.entry_set is a Manager that returns QuerySets.
  840. >>> b.entry_set.filter(headline__contains='Lennon')
  841. >>> b.entry_set.count()
  842. You can override the ``FOO_set`` name by setting the
  843. :attr:`~django.db.models.ForeignKey.related_name` parameter in the
  844. :class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``
  845. model was altered to ``blog = ForeignKey(Blog, on_delete=models.CASCADE,
  846. related_name='entries')``, the above example code would look like this::
  847. >>> b = Blog.objects.get(id=1)
  848. >>> b.entries.all() # Returns all Entry objects related to Blog.
  849. # b.entries is a Manager that returns QuerySets.
  850. >>> b.entries.filter(headline__contains='Lennon')
  851. >>> b.entries.count()
  852. .. _using-custom-reverse-manager:
  853. Using a custom reverse manager
  854. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  855. By default the :class:`~django.db.models.fields.related.RelatedManager` used
  856. for reverse relations is a subclass of the :ref:`default manager <manager-names>`
  857. for that model. If you would like to specify a different manager for a given
  858. query you can use the following syntax::
  859. from django.db import models
  860. class Entry(models.Model):
  861. #...
  862. objects = models.Manager() # Default Manager
  863. entries = EntryManager() # Custom Manager
  864. b = Blog.objects.get(id=1)
  865. b.entry_set(manager='entries').all()
  866. If ``EntryManager`` performed default filtering in its ``get_queryset()``
  867. method, that filtering would apply to the ``all()`` call.
  868. Of course, specifying a custom reverse manager also enables you to call its
  869. custom methods::
  870. b.entry_set(manager='entries').is_published()
  871. Additional methods to handle related objects
  872. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  873. In addition to the :class:`~django.db.models.query.QuerySet` methods defined in
  874. "Retrieving objects" above, the :class:`~django.db.models.ForeignKey`
  875. :class:`~django.db.models.Manager` has additional methods used to handle the
  876. set of related objects. A synopsis of each is below, and complete details can
  877. be found in the :doc:`related objects reference </ref/models/relations>`.
  878. ``add(obj1, obj2, ...)``
  879. Adds the specified model objects to the related object set.
  880. ``create(**kwargs)``
  881. Creates a new object, saves it and puts it in the related object set.
  882. Returns the newly created object.
  883. ``remove(obj1, obj2, ...)``
  884. Removes the specified model objects from the related object set.
  885. ``clear()``
  886. Removes all objects from the related object set.
  887. ``set(objs)``
  888. Replace the set of related objects.
  889. To assign the members of a related set, use the ``set()`` method with an
  890. iterable of object instances or a list of primary key values. For example::
  891. b = Blog.objects.get(id=1)
  892. b.entry_set.set([e1, e2])
  893. In this example, ``e1`` and ``e2`` can be full Entry instances, or integer
  894. primary key values.
  895. If the ``clear()`` method is available, any pre-existing objects will be
  896. removed from the ``entry_set`` before all objects in the iterable (in this
  897. case, a list) are added to the set. If the ``clear()`` method is *not*
  898. available, all objects in the iterable will be added without removing any
  899. existing elements.
  900. Each "reverse" operation described in this section has an immediate effect on
  901. the database. Every addition, creation and deletion is immediately and
  902. automatically saved to the database.
  903. .. _m2m-reverse-relationships:
  904. Many-to-many relationships
  905. --------------------------
  906. Both ends of a many-to-many relationship get automatic API access to the other
  907. end. The API works just as a "backward" one-to-many relationship, above.
  908. The only difference is in the attribute naming: The model that defines the
  909. :class:`~django.db.models.ManyToManyField` uses the attribute name of that
  910. field itself, whereas the "reverse" model uses the lowercased model name of the
  911. original model, plus ``'_set'`` (just like reverse one-to-many relationships).
  912. An example makes this easier to understand::
  913. e = Entry.objects.get(id=3)
  914. e.authors.all() # Returns all Author objects for this Entry.
  915. e.authors.count()
  916. e.authors.filter(name__contains='John')
  917. a = Author.objects.get(id=5)
  918. a.entry_set.all() # Returns all Entry objects for this Author.
  919. Like :class:`~django.db.models.ForeignKey`,
  920. :class:`~django.db.models.ManyToManyField` can specify
  921. :attr:`~django.db.models.ManyToManyField.related_name`. In the above example,
  922. if the :class:`~django.db.models.ManyToManyField` in ``Entry`` had specified
  923. ``related_name='entries'``, then each ``Author`` instance would have an
  924. ``entries`` attribute instead of ``entry_set``.
  925. One-to-one relationships
  926. ------------------------
  927. One-to-one relationships are very similar to many-to-one relationships. If you
  928. define a :class:`~django.db.models.OneToOneField` on your model, instances of
  929. that model will have access to the related object via a simple attribute of the
  930. model.
  931. For example::
  932. class EntryDetail(models.Model):
  933. entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
  934. details = models.TextField()
  935. ed = EntryDetail.objects.get(id=2)
  936. ed.entry # Returns the related Entry object.
  937. The difference comes in "reverse" queries. The related model in a one-to-one
  938. relationship also has access to a :class:`~django.db.models.Manager` object, but
  939. that :class:`~django.db.models.Manager` represents a single object, rather than
  940. a collection of objects::
  941. e = Entry.objects.get(id=2)
  942. e.entrydetail # returns the related EntryDetail object
  943. If no object has been assigned to this relationship, Django will raise
  944. a ``DoesNotExist`` exception.
  945. Instances can be assigned to the reverse relationship in the same way as
  946. you would assign the forward relationship::
  947. e.entrydetail = ed
  948. How are the backward relationships possible?
  949. --------------------------------------------
  950. Other object-relational mappers require you to define relationships on both
  951. sides. The Django developers believe this is a violation of the DRY (Don't
  952. Repeat Yourself) principle, so Django only requires you to define the
  953. relationship on one end.
  954. But how is this possible, given that a model class doesn't know which other
  955. model classes are related to it until those other model classes are loaded?
  956. The answer lies in the :data:`app registry <django.apps.apps>`. When Django
  957. starts, it imports each application listed in :setting:`INSTALLED_APPS`, and
  958. then the ``models`` module inside each application. Whenever a new model class
  959. is created, Django adds backward-relationships to any related models. If the
  960. related models haven't been imported yet, Django keeps tracks of the
  961. relationships and adds them when the related models eventually are imported.
  962. For this reason, it's particularly important that all the models you're using
  963. be defined in applications listed in :setting:`INSTALLED_APPS`. Otherwise,
  964. backwards relations may not work properly.
  965. Queries over related objects
  966. ----------------------------
  967. Queries involving related objects follow the same rules as queries involving
  968. normal value fields. When specifying the value for a query to match, you may
  969. use either an object instance itself, or the primary key value for the object.
  970. For example, if you have a Blog object ``b`` with ``id=5``, the following
  971. three queries would be identical::
  972. Entry.objects.filter(blog=b) # Query using object instance
  973. Entry.objects.filter(blog=b.id) # Query using id from instance
  974. Entry.objects.filter(blog=5) # Query using id directly
  975. Falling back to raw SQL
  976. =======================
  977. If you find yourself needing to write an SQL query that is too complex for
  978. Django's database-mapper to handle, you can fall back on writing SQL by hand.
  979. Django has a couple of options for writing raw SQL queries; see
  980. :doc:`/topics/db/sql`.
  981. Finally, it's important to note that the Django database layer is merely an
  982. interface to your database. You can access your database via other tools,
  983. programming languages or database frameworks; there's nothing Django-specific
  984. about your database.