queries.txt 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  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, on_delete=models.CASCADE)
  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. number_of_comments = models.IntegerField()
  33. number_of_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 -- assign an object of the right type to the field
  71. in question. This example updates the ``blog`` attribute of an ``Entry``
  72. instance ``entry``, assuming appropriate instances of ``Entry`` and ``Blog``
  73. 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.date(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 an index instead of a slice. For
  272. example, this returns the first ``Entry`` in the database, after ordering
  273. 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, 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, 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(number_of_comments__gt=F('number_of_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(number_of_comments__gt=F('number_of_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('number_of_comments') + F('number_of_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. ``.bitxor()``, ``.bitrightshift()``, and ``.bitleftshift()``. For example::
  478. >>> F('somefield').bitand(16)
  479. .. admonition:: Oracle
  480. Oracle doesn't support bitwise XOR operation.
  481. .. versionchanged:: 3.1
  482. Support for ``.bitxor()`` was added.
  483. The ``pk`` lookup shortcut
  484. --------------------------
  485. For convenience, Django provides a ``pk`` lookup shortcut, which stands for
  486. "primary key".
  487. In the example ``Blog`` model, the primary key is the ``id`` field, so these
  488. three statements are equivalent::
  489. >>> Blog.objects.get(id__exact=14) # Explicit form
  490. >>> Blog.objects.get(id=14) # __exact is implied
  491. >>> Blog.objects.get(pk=14) # pk implies id__exact
  492. The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
  493. can be combined with ``pk`` to perform a query on the primary key of a model::
  494. # Get blogs entries with id 1, 4 and 7
  495. >>> Blog.objects.filter(pk__in=[1,4,7])
  496. # Get all blog entries with id > 14
  497. >>> Blog.objects.filter(pk__gt=14)
  498. ``pk`` lookups also work across joins. For example, these three statements are
  499. equivalent::
  500. >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
  501. >>> Entry.objects.filter(blog__id=3) # __exact is implied
  502. >>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
  503. Escaping percent signs and underscores in ``LIKE`` statements
  504. -------------------------------------------------------------
  505. The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
  506. ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
  507. and ``iendswith``) will automatically escape the two special characters used in
  508. ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
  509. statement, the percent sign signifies a multiple-character wildcard and the
  510. underscore signifies a single-character wildcard.)
  511. This means things should work intuitively, so the abstraction doesn't leak.
  512. For example, to retrieve all the entries that contain a percent sign, use the
  513. percent sign as any other character::
  514. >>> Entry.objects.filter(headline__contains='%')
  515. Django takes care of the quoting for you; the resulting SQL will look something
  516. like this:
  517. .. code-block:: sql
  518. SELECT ... WHERE headline LIKE '%\%%';
  519. Same goes for underscores. Both percentage signs and underscores are handled
  520. for you transparently.
  521. .. _caching-and-querysets:
  522. Caching and ``QuerySet``\s
  523. --------------------------
  524. Each :class:`~django.db.models.query.QuerySet` contains a cache to minimize
  525. database access. Understanding how it works will allow you to write the most
  526. efficient code.
  527. In a newly created :class:`~django.db.models.query.QuerySet`, the cache is
  528. empty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated
  529. -- and, hence, a database query happens -- Django saves the query results in
  530. the :class:`~django.db.models.query.QuerySet`’s cache and returns the results
  531. that have been explicitly requested (e.g., the next element, if the
  532. :class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent
  533. evaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached
  534. results.
  535. Keep this caching behavior in mind, because it may bite you if you don't use
  536. your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
  537. following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
  538. them, and throw them away::
  539. >>> print([e.headline for e in Entry.objects.all()])
  540. >>> print([e.pub_date for e in Entry.objects.all()])
  541. That means the same database query will be executed twice, effectively doubling
  542. your database load. Also, there's a possibility the two lists may not include
  543. the same database records, because an ``Entry`` may have been added or deleted
  544. in the split second between the two requests.
  545. To avoid this problem, save the :class:`~django.db.models.query.QuerySet` and
  546. reuse it::
  547. >>> queryset = Entry.objects.all()
  548. >>> print([p.headline for p in queryset]) # Evaluate the query set.
  549. >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
  550. When ``QuerySet``\s are not cached
  551. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  552. Querysets do not always cache their results. When evaluating only *part* of
  553. the queryset, the cache is checked, but if it is not populated then the items
  554. returned by the subsequent query are not cached. Specifically, this means that
  555. :ref:`limiting the queryset <limiting-querysets>` using an array slice or an
  556. index will not populate the cache.
  557. For example, repeatedly getting a certain index in a queryset object will query
  558. the database each time::
  559. >>> queryset = Entry.objects.all()
  560. >>> print(queryset[5]) # Queries the database
  561. >>> print(queryset[5]) # Queries the database again
  562. However, if the entire queryset has already been evaluated, the cache will be
  563. checked instead::
  564. >>> queryset = Entry.objects.all()
  565. >>> [entry for entry in queryset] # Queries the database
  566. >>> print(queryset[5]) # Uses cache
  567. >>> print(queryset[5]) # Uses cache
  568. Here are some examples of other actions that will result in the entire queryset
  569. being evaluated and therefore populate the cache::
  570. >>> [entry for entry in queryset]
  571. >>> bool(queryset)
  572. >>> entry in queryset
  573. >>> list(queryset)
  574. .. note::
  575. Simply printing the queryset will not populate the cache. This is because
  576. the call to ``__repr__()`` only returns a slice of the entire queryset.
  577. .. _querying-jsonfield:
  578. Querying ``JSONField``
  579. ======================
  580. Lookups implementation is different in :class:`~django.db.models.JSONField`,
  581. mainly due to the existence of key transformations. To demonstrate, we will use
  582. the following example model::
  583. from django.db import models
  584. class Dog(models.Model):
  585. name = models.CharField(max_length=200)
  586. data = models.JSONField(null=True)
  587. def __str__(self):
  588. return self.name
  589. Storing and querying for ``None``
  590. ---------------------------------
  591. As with other fields, storing ``None`` as the field's value will store it as
  592. SQL ``NULL``. While not recommended, it is possible to store JSON scalar
  593. ``null`` instead of SQL ``NULL`` by using :class:`Value('null')
  594. <django.db.models.Value>`.
  595. Whichever of the values is stored, when retrieved from the database, the Python
  596. representation of the JSON scalar ``null`` is the same as SQL ``NULL``, i.e.
  597. ``None``. Therefore, it can be hard to distinguish between them.
  598. This only applies to ``None`` as the top-level value of the field. If ``None``
  599. is inside a :py:class:`list` or :py:class:`dict`, it will always be interpreted
  600. as JSON ``null``.
  601. When querying, ``None`` value will always be interpreted as JSON ``null``. To
  602. query for SQL ``NULL``, use :lookup:`isnull`::
  603. >>> Dog.objects.create(name='Max', data=None) # SQL NULL.
  604. <Dog: Max>
  605. >>> Dog.objects.create(name='Archie', data=Value('null')) # JSON null.
  606. <Dog: Archie>
  607. >>> Dog.objects.filter(data=None)
  608. <QuerySet [<Dog: Archie>]>
  609. >>> Dog.objects.filter(data=Value('null'))
  610. <QuerySet [<Dog: Archie>]>
  611. >>> Dog.objects.filter(data__isnull=True)
  612. <QuerySet [<Dog: Max>]>
  613. >>> Dog.objects.filter(data__isnull=False)
  614. <QuerySet [<Dog: Archie>]>
  615. Unless you are sure you wish to work with SQL ``NULL`` values, consider setting
  616. ``null=False`` and providing a suitable default for empty values, such as
  617. ``default=dict``.
  618. .. note::
  619. Storing JSON scalar ``null`` does not violate :attr:`null=False
  620. <django.db.models.Field.null>`.
  621. .. fieldlookup:: jsonfield.key
  622. Key, index, and path transforms
  623. -------------------------------
  624. To query based on a given dictionary key, use that key as the lookup name::
  625. >>> Dog.objects.create(name='Rufus', data={
  626. ... 'breed': 'labrador',
  627. ... 'owner': {
  628. ... 'name': 'Bob',
  629. ... 'other_pets': [{
  630. ... 'name': 'Fishy',
  631. ... }],
  632. ... },
  633. ... })
  634. <Dog: Rufus>
  635. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': None})
  636. <Dog: Meg>
  637. >>> Dog.objects.filter(data__breed='collie')
  638. <QuerySet [<Dog: Meg>]>
  639. Multiple keys can be chained together to form a path lookup::
  640. >>> Dog.objects.filter(data__owner__name='Bob')
  641. <QuerySet [<Dog: Rufus>]>
  642. If the key is an integer, it will be interpreted as an index transform in an
  643. array::
  644. >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
  645. <QuerySet [<Dog: Rufus>]>
  646. If the key you wish to query by clashes with the name of another lookup, use
  647. the :lookup:`contains <jsonfield.contains>` lookup instead.
  648. To query for missing keys, use the ``isnull`` lookup::
  649. >>> Dog.objects.create(name='Shep', data={'breed': 'collie'})
  650. <Dog: Shep>
  651. >>> Dog.objects.filter(data__owner__isnull=True)
  652. <QuerySet [<Dog: Shep>]>
  653. .. note::
  654. The lookup examples given above implicitly use the :lookup:`exact` lookup.
  655. Key, index, and path transforms can also be chained with:
  656. :lookup:`contains`, :lookup:`icontains`, :lookup:`endswith`,
  657. :lookup:`iendswith`, :lookup:`iexact`, :lookup:`regex`, :lookup:`iregex`,
  658. :lookup:`startswith`, :lookup:`istartswith`, :lookup:`lt`, :lookup:`lte`,
  659. :lookup:`gt`, and :lookup:`gte` lookups.
  660. .. warning::
  661. Since any string could be a key in a JSON object, any lookup other than
  662. those listed below will be interpreted as a key lookup. No errors are
  663. raised. Be extra careful for typing mistakes, and always check your queries
  664. work as you intend.
  665. .. admonition:: MariaDB and Oracle users
  666. Using :meth:`~django.db.models.query.QuerySet.order_by` on key, index, or
  667. path transforms will sort the objects using the string representation of
  668. the values. This is because MariaDB and Oracle Database do not provide a
  669. function that converts JSON values into their equivalent SQL values.
  670. .. admonition:: Oracle users
  671. On Oracle Database, using ``None`` as the lookup value in an
  672. :meth:`~django.db.models.query.QuerySet.exclude` query will return objects
  673. that do not have ``null`` as the value at the given path, including objects
  674. that do not have the path. On other database backends, the query will
  675. return objects that have the path and the value is not ``null``.
  676. .. admonition:: PostgreSQL users
  677. On PostgreSQL, if only one key or index is used, the SQL operator ``->`` is
  678. used. If multiple operators are used then the ``#>`` operator is used.
  679. Containment and key operations
  680. ------------------------------
  681. .. fieldlookup:: jsonfield.contains
  682. ``contains``
  683. ~~~~~~~~~~~~
  684. The :lookup:`contains` lookup is overridden on ``JSONField``. The returned
  685. objects are those where the given ``dict`` of key-value pairs are all
  686. contained in the top-level of the field. For example::
  687. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
  688. <Dog: Rufus>
  689. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  690. <Dog: Meg>
  691. >>> Dog.objects.create(name='Fred', data={})
  692. <Dog: Fred>
  693. >>> Dog.objects.filter(data__contains={'owner': 'Bob'})
  694. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  695. >>> Dog.objects.filter(data__contains={'breed': 'collie'})
  696. <QuerySet [<Dog: Meg>]>
  697. .. fieldlookup:: jsonfield.contained_by
  698. ``contained_by``
  699. ~~~~~~~~~~~~~~~~
  700. This is the inverse of the :lookup:`contains <jsonfield.contains>` lookup - the
  701. objects returned will be those where the key-value pairs on the object are a
  702. subset of those in the value passed. For example::
  703. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
  704. <Dog: Rufus>
  705. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  706. <Dog: Meg>
  707. >>> Dog.objects.create(name='Fred', data={})
  708. <Dog: Fred>
  709. >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})
  710. <QuerySet [<Dog: Meg>, <Dog: Fred>]>
  711. >>> Dog.objects.filter(data__contained_by={'breed': 'collie'})
  712. <QuerySet [<Dog: Fred>]>
  713. .. admonition:: Oracle
  714. ``contained_by`` is not supported on Oracle.
  715. .. fieldlookup:: jsonfield.has_key
  716. ``has_key``
  717. ~~~~~~~~~~~
  718. Returns objects where the given key is in the top-level of the data. For
  719. example::
  720. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  721. <Dog: Rufus>
  722. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  723. <Dog: Meg>
  724. >>> Dog.objects.filter(data__has_key='owner')
  725. <QuerySet [<Dog: Meg>]>
  726. .. fieldlookup:: jsonfield.has_any_keys
  727. ``has_keys``
  728. ~~~~~~~~~~~~
  729. Returns objects where all of the given keys are in the top-level of the data.
  730. For example::
  731. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  732. <Dog: Rufus>
  733. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  734. <Dog: Meg>
  735. >>> Dog.objects.filter(data__has_keys=['breed', 'owner'])
  736. <QuerySet [<Dog: Meg>]>
  737. .. fieldlookup:: jsonfield.has_keys
  738. ``has_any_keys``
  739. ~~~~~~~~~~~~~~~~
  740. Returns objects where any of the given keys are in the top-level of the data.
  741. For example::
  742. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  743. <Dog: Rufus>
  744. >>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
  745. <Dog: Meg>
  746. >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])
  747. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  748. .. _complex-lookups-with-q:
  749. Complex lookups with ``Q`` objects
  750. ==================================
  751. Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
  752. etc. -- are "AND"ed together. If you need to execute more complex queries (for
  753. example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.
  754. A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object
  755. used to encapsulate a collection of keyword arguments. These keyword arguments
  756. are specified as in "Field lookups" above.
  757. For example, this ``Q`` object encapsulates a single ``LIKE`` query::
  758. from django.db.models import Q
  759. Q(question__startswith='What')
  760. ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
  761. operator is used on two ``Q`` objects, it yields a new ``Q`` object.
  762. For example, this statement yields a single ``Q`` object that represents the
  763. "OR" of two ``"question__startswith"`` queries::
  764. Q(question__startswith='Who') | Q(question__startswith='What')
  765. This is equivalent to the following SQL ``WHERE`` clause::
  766. WHERE question LIKE 'Who%' OR question LIKE 'What%'
  767. You can compose statements of arbitrary complexity by combining ``Q`` objects
  768. with the ``&`` and ``|`` operators and use parenthetical grouping. Also, ``Q``
  769. objects can be negated using the ``~`` operator, allowing for combined lookups
  770. that combine both a normal query and a negated (``NOT``) query::
  771. Q(question__startswith='Who') | ~Q(pub_date__year=2005)
  772. Each lookup function that takes keyword-arguments
  773. (e.g. :meth:`~django.db.models.query.QuerySet.filter`,
  774. :meth:`~django.db.models.query.QuerySet.exclude`,
  775. :meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more
  776. ``Q`` objects as positional (not-named) arguments. If you provide multiple
  777. ``Q`` object arguments to a lookup function, the arguments will be "AND"ed
  778. together. For example::
  779. Poll.objects.get(
  780. Q(question__startswith='Who'),
  781. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
  782. )
  783. ... roughly translates into the SQL:
  784. .. code-block:: sql
  785. SELECT * from polls WHERE question LIKE 'Who%'
  786. AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
  787. Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
  788. arguments provided to a lookup function (be they keyword arguments or ``Q``
  789. objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
  790. precede the definition of any keyword arguments. For example::
  791. Poll.objects.get(
  792. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
  793. question__startswith='Who',
  794. )
  795. ... would be a valid query, equivalent to the previous example; but::
  796. # INVALID QUERY
  797. Poll.objects.get(
  798. question__startswith='Who',
  799. Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
  800. )
  801. ... would not be valid.
  802. .. seealso::
  803. The :source:`OR lookups examples <tests/or_lookups/tests.py>` in Django's
  804. unit tests show some possible uses of ``Q``.
  805. Comparing objects
  806. =================
  807. To compare two model instances, use the standard Python comparison operator,
  808. the double equals sign: ``==``. Behind the scenes, that compares the primary
  809. key values of two models.
  810. Using the ``Entry`` example above, the following two statements are equivalent::
  811. >>> some_entry == other_entry
  812. >>> some_entry.id == other_entry.id
  813. If a model's primary key isn't called ``id``, no problem. Comparisons will
  814. always use the primary key, whatever it's called. For example, if a model's
  815. primary key field is called ``name``, these two statements are equivalent::
  816. >>> some_obj == other_obj
  817. >>> some_obj.name == other_obj.name
  818. .. _topics-db-queries-delete:
  819. Deleting objects
  820. ================
  821. The delete method, conveniently, is named
  822. :meth:`~django.db.models.Model.delete`. This method immediately deletes the
  823. object and returns the number of objects deleted and a dictionary with
  824. the number of deletions per object type. Example::
  825. >>> e.delete()
  826. (1, {'weblog.Entry': 1})
  827. You can also delete objects in bulk. Every
  828. :class:`~django.db.models.query.QuerySet` has a
  829. :meth:`~django.db.models.query.QuerySet.delete` method, which deletes all
  830. members of that :class:`~django.db.models.query.QuerySet`.
  831. For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
  832. 2005::
  833. >>> Entry.objects.filter(pub_date__year=2005).delete()
  834. (5, {'webapp.Entry': 5})
  835. Keep in mind that this will, whenever possible, be executed purely in SQL, and
  836. so the ``delete()`` methods of individual object instances will not necessarily
  837. be called during the process. If you've provided a custom ``delete()`` method
  838. on a model class and want to ensure that it is called, you will need to
  839. "manually" delete instances of that model (e.g., by iterating over a
  840. :class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each
  841. object individually) rather than using the bulk
  842. :meth:`~django.db.models.query.QuerySet.delete` method of a
  843. :class:`~django.db.models.query.QuerySet`.
  844. When Django deletes an object, by default it emulates the behavior of the SQL
  845. constraint ``ON DELETE CASCADE`` -- in other words, any objects which had
  846. foreign keys pointing at the object to be deleted will be deleted along with
  847. it. For example::
  848. b = Blog.objects.get(pk=1)
  849. # This will delete the Blog and all of its Entry objects.
  850. b.delete()
  851. This cascade behavior is customizable via the
  852. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  853. :class:`~django.db.models.ForeignKey`.
  854. Note that :meth:`~django.db.models.query.QuerySet.delete` is the only
  855. :class:`~django.db.models.query.QuerySet` method that is not exposed on a
  856. :class:`~django.db.models.Manager` itself. This is a safety mechanism to
  857. prevent you from accidentally requesting ``Entry.objects.delete()``, and
  858. deleting *all* the entries. If you *do* want to delete all the objects, then
  859. you have to explicitly request a complete query set::
  860. Entry.objects.all().delete()
  861. .. _topics-db-queries-copy:
  862. Copying model instances
  863. =======================
  864. Although there is no built-in method for copying model instances, it is
  865. possible to easily create new instance with all fields' values copied. In the
  866. simplest case, you can set ``pk`` to ``None``. Using our blog example::
  867. blog = Blog(name='My blog', tagline='Blogging is easy')
  868. blog.save() # blog.pk == 1
  869. blog.pk = None
  870. blog.save() # blog.pk == 2
  871. Things get more complicated if you use inheritance. Consider a subclass of
  872. ``Blog``::
  873. class ThemeBlog(Blog):
  874. theme = models.CharField(max_length=200)
  875. django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')
  876. django_blog.save() # django_blog.pk == 3
  877. Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::
  878. django_blog.pk = None
  879. django_blog.id = None
  880. django_blog.save() # django_blog.pk == 4
  881. This process doesn't copy relations that aren't part of the model's database
  882. table. For example, ``Entry`` has a ``ManyToManyField`` to ``Author``. After
  883. duplicating an entry, you must set the many-to-many relations for the new
  884. entry::
  885. entry = Entry.objects.all()[0] # some previous entry
  886. old_authors = entry.authors.all()
  887. entry.pk = None
  888. entry.save()
  889. entry.authors.set(old_authors)
  890. For a ``OneToOneField``, you must duplicate the related object and assign it
  891. to the new object's field to avoid violating the one-to-one unique constraint.
  892. For example, assuming ``entry`` is already duplicated as above::
  893. detail = EntryDetail.objects.all()[0]
  894. detail.pk = None
  895. detail.entry = entry
  896. detail.save()
  897. .. _topics-db-queries-update:
  898. Updating multiple objects at once
  899. =================================
  900. Sometimes you want to set a field to a particular value for all the objects in
  901. a :class:`~django.db.models.query.QuerySet`. You can do this with the
  902. :meth:`~django.db.models.query.QuerySet.update` method. For example::
  903. # Update all the headlines with pub_date in 2007.
  904. Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
  905. You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
  906. fields using this method. To update a non-relation field, provide the new value
  907. as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
  908. new value to be the new model instance you want to point to. For example::
  909. >>> b = Blog.objects.get(pk=1)
  910. # Change every Entry so that it belongs to this Blog.
  911. >>> Entry.objects.all().update(blog=b)
  912. The ``update()`` method is applied instantly and returns the number of rows
  913. matched by the query (which may not be equal to the number of rows updated if
  914. some rows already have the new value). The only restriction on the
  915. :class:`~django.db.models.query.QuerySet` being updated is that it can only
  916. access one database table: the model's main table. You can filter based on
  917. related fields, but you can only update columns in the model's main
  918. table. Example::
  919. >>> b = Blog.objects.get(pk=1)
  920. # Update all the headlines belonging to this Blog.
  921. >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
  922. Be aware that the ``update()`` method is converted directly to an SQL
  923. statement. It is a bulk operation for direct updates. It doesn't run any
  924. :meth:`~django.db.models.Model.save` methods on your models, or emit the
  925. ``pre_save`` or ``post_save`` signals (which are a consequence of calling
  926. :meth:`~django.db.models.Model.save`), or honor the
  927. :attr:`~django.db.models.DateField.auto_now` field option.
  928. If you want to save every item in a :class:`~django.db.models.query.QuerySet`
  929. and make sure that the :meth:`~django.db.models.Model.save` method is called on
  930. each instance, you don't need any special function to handle that. Loop over
  931. them and call :meth:`~django.db.models.Model.save`::
  932. for item in my_queryset:
  933. item.save()
  934. Calls to update can also use :class:`F expressions <django.db.models.F>` to
  935. update one field based on the value of another field in the model. This is
  936. especially useful for incrementing counters based upon their current value. For
  937. example, to increment the pingback count for every entry in the blog::
  938. >>> Entry.objects.all().update(number_of_pingbacks=F('number_of_pingbacks') + 1)
  939. However, unlike ``F()`` objects in filter and exclude clauses, you can't
  940. introduce joins when you use ``F()`` objects in an update -- you can only
  941. reference fields local to the model being updated. If you attempt to introduce
  942. a join with an ``F()`` object, a ``FieldError`` will be raised::
  943. # This will raise a FieldError
  944. >>> Entry.objects.update(headline=F('blog__name'))
  945. .. _topics-db-queries-related:
  946. Related objects
  947. ===============
  948. When you define a relationship in a model (i.e., a
  949. :class:`~django.db.models.ForeignKey`,
  950. :class:`~django.db.models.OneToOneField`, or
  951. :class:`~django.db.models.ManyToManyField`), instances of that model will have
  952. a convenient API to access the related object(s).
  953. Using the models at the top of this page, for example, an ``Entry`` object ``e``
  954. can get its associated ``Blog`` object by accessing the ``blog`` attribute:
  955. ``e.blog``.
  956. (Behind the scenes, this functionality is implemented by Python descriptors_.
  957. This shouldn't really matter to you, but we point it out here for the curious.)
  958. Django also creates API accessors for the "other" side of the relationship --
  959. the link from the related model to the model that defines the relationship.
  960. For example, a ``Blog`` object ``b`` has access to a list of all related
  961. ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
  962. All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
  963. models defined at the top of this page.
  964. .. _descriptors: https://docs.python.org/howto/descriptor.html
  965. One-to-many relationships
  966. -------------------------
  967. Forward
  968. ~~~~~~~
  969. If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
  970. will have access to the related (foreign) object via an attribute of the model.
  971. Example::
  972. >>> e = Entry.objects.get(id=2)
  973. >>> e.blog # Returns the related Blog object.
  974. You can get and set via a foreign-key attribute. As you may expect, changes to
  975. the foreign key aren't saved to the database until you call
  976. :meth:`~django.db.models.Model.save`. Example::
  977. >>> e = Entry.objects.get(id=2)
  978. >>> e.blog = some_blog
  979. >>> e.save()
  980. If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,
  981. it allows ``NULL`` values), you can assign ``None`` to remove the relation.
  982. Example::
  983. >>> e = Entry.objects.get(id=2)
  984. >>> e.blog = None
  985. >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
  986. Forward access to one-to-many relationships is cached the first time the
  987. related object is accessed. Subsequent accesses to the foreign key on the same
  988. object instance are cached. Example::
  989. >>> e = Entry.objects.get(id=2)
  990. >>> print(e.blog) # Hits the database to retrieve the associated Blog.
  991. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  992. Note that the :meth:`~django.db.models.query.QuerySet.select_related`
  993. :class:`~django.db.models.query.QuerySet` method recursively prepopulates the
  994. cache of all one-to-many relationships ahead of time. Example::
  995. >>> e = Entry.objects.select_related().get(id=2)
  996. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  997. >>> print(e.blog) # Doesn't hit the database; uses cached version.
  998. .. _backwards-related-objects:
  999. Following relationships "backward"
  1000. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1001. If a model has a :class:`~django.db.models.ForeignKey`, instances of the
  1002. foreign-key model will have access to a :class:`~django.db.models.Manager` that
  1003. returns all instances of the first model. By default, this
  1004. :class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the
  1005. source model name, lowercased. This :class:`~django.db.models.Manager` returns
  1006. ``QuerySets``, which can be filtered and manipulated as described in the
  1007. "Retrieving objects" section above.
  1008. Example::
  1009. >>> b = Blog.objects.get(id=1)
  1010. >>> b.entry_set.all() # Returns all Entry objects related to Blog.
  1011. # b.entry_set is a Manager that returns QuerySets.
  1012. >>> b.entry_set.filter(headline__contains='Lennon')
  1013. >>> b.entry_set.count()
  1014. You can override the ``FOO_set`` name by setting the
  1015. :attr:`~django.db.models.ForeignKey.related_name` parameter in the
  1016. :class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``
  1017. model was altered to ``blog = ForeignKey(Blog, on_delete=models.CASCADE,
  1018. related_name='entries')``, the above example code would look like this::
  1019. >>> b = Blog.objects.get(id=1)
  1020. >>> b.entries.all() # Returns all Entry objects related to Blog.
  1021. # b.entries is a Manager that returns QuerySets.
  1022. >>> b.entries.filter(headline__contains='Lennon')
  1023. >>> b.entries.count()
  1024. .. _using-custom-reverse-manager:
  1025. Using a custom reverse manager
  1026. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1027. By default the :class:`~django.db.models.fields.related.RelatedManager` used
  1028. for reverse relations is a subclass of the :ref:`default manager <manager-names>`
  1029. for that model. If you would like to specify a different manager for a given
  1030. query you can use the following syntax::
  1031. from django.db import models
  1032. class Entry(models.Model):
  1033. #...
  1034. objects = models.Manager() # Default Manager
  1035. entries = EntryManager() # Custom Manager
  1036. b = Blog.objects.get(id=1)
  1037. b.entry_set(manager='entries').all()
  1038. If ``EntryManager`` performed default filtering in its ``get_queryset()``
  1039. method, that filtering would apply to the ``all()`` call.
  1040. Specifying a custom reverse manager also enables you to call its custom
  1041. methods::
  1042. b.entry_set(manager='entries').is_published()
  1043. Additional methods to handle related objects
  1044. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1045. In addition to the :class:`~django.db.models.query.QuerySet` methods defined in
  1046. "Retrieving objects" above, the :class:`~django.db.models.ForeignKey`
  1047. :class:`~django.db.models.Manager` has additional methods used to handle the
  1048. set of related objects. A synopsis of each is below, and complete details can
  1049. be found in the :doc:`related objects reference </ref/models/relations>`.
  1050. ``add(obj1, obj2, ...)``
  1051. Adds the specified model objects to the related object set.
  1052. ``create(**kwargs)``
  1053. Creates a new object, saves it and puts it in the related object set.
  1054. Returns the newly created object.
  1055. ``remove(obj1, obj2, ...)``
  1056. Removes the specified model objects from the related object set.
  1057. ``clear()``
  1058. Removes all objects from the related object set.
  1059. ``set(objs)``
  1060. Replace the set of related objects.
  1061. To assign the members of a related set, use the ``set()`` method with an
  1062. iterable of object instances. For example, if ``e1`` and ``e2`` are ``Entry``
  1063. instances::
  1064. b = Blog.objects.get(id=1)
  1065. b.entry_set.set([e1, e2])
  1066. If the ``clear()`` method is available, any pre-existing objects will be
  1067. removed from the ``entry_set`` before all objects in the iterable (in this
  1068. case, a list) are added to the set. If the ``clear()`` method is *not*
  1069. available, all objects in the iterable will be added without removing any
  1070. existing elements.
  1071. Each "reverse" operation described in this section has an immediate effect on
  1072. the database. Every addition, creation and deletion is immediately and
  1073. automatically saved to the database.
  1074. .. _m2m-reverse-relationships:
  1075. Many-to-many relationships
  1076. --------------------------
  1077. Both ends of a many-to-many relationship get automatic API access to the other
  1078. end. The API works similar to a "backward" one-to-many relationship, above.
  1079. One difference is in the attribute naming: The model that defines the
  1080. :class:`~django.db.models.ManyToManyField` uses the attribute name of that
  1081. field itself, whereas the "reverse" model uses the lowercased model name of the
  1082. original model, plus ``'_set'`` (just like reverse one-to-many relationships).
  1083. An example makes this easier to understand::
  1084. e = Entry.objects.get(id=3)
  1085. e.authors.all() # Returns all Author objects for this Entry.
  1086. e.authors.count()
  1087. e.authors.filter(name__contains='John')
  1088. a = Author.objects.get(id=5)
  1089. a.entry_set.all() # Returns all Entry objects for this Author.
  1090. Like :class:`~django.db.models.ForeignKey`,
  1091. :class:`~django.db.models.ManyToManyField` can specify
  1092. :attr:`~django.db.models.ManyToManyField.related_name`. In the above example,
  1093. if the :class:`~django.db.models.ManyToManyField` in ``Entry`` had specified
  1094. ``related_name='entries'``, then each ``Author`` instance would have an
  1095. ``entries`` attribute instead of ``entry_set``.
  1096. Another difference from one-to-many relationships is that in addition to model
  1097. instances, the ``add()``, ``set()``, and ``remove()`` methods on many-to-many
  1098. relationships accept primary key values. For example, if ``e1`` and ``e2`` are
  1099. ``Entry`` instances, then these ``set()`` calls work identically::
  1100. a = Author.objects.get(id=5)
  1101. a.entry_set.set([e1, e2])
  1102. a.entry_set.set([e1.pk, e2.pk])
  1103. One-to-one relationships
  1104. ------------------------
  1105. One-to-one relationships are very similar to many-to-one relationships. If you
  1106. define a :class:`~django.db.models.OneToOneField` on your model, instances of
  1107. that model will have access to the related object via an attribute of the
  1108. model.
  1109. For example::
  1110. class EntryDetail(models.Model):
  1111. entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
  1112. details = models.TextField()
  1113. ed = EntryDetail.objects.get(id=2)
  1114. ed.entry # Returns the related Entry object.
  1115. The difference comes in "reverse" queries. The related model in a one-to-one
  1116. relationship also has access to a :class:`~django.db.models.Manager` object, but
  1117. that :class:`~django.db.models.Manager` represents a single object, rather than
  1118. a collection of objects::
  1119. e = Entry.objects.get(id=2)
  1120. e.entrydetail # returns the related EntryDetail object
  1121. If no object has been assigned to this relationship, Django will raise
  1122. a ``DoesNotExist`` exception.
  1123. Instances can be assigned to the reverse relationship in the same way as
  1124. you would assign the forward relationship::
  1125. e.entrydetail = ed
  1126. How are the backward relationships possible?
  1127. --------------------------------------------
  1128. Other object-relational mappers require you to define relationships on both
  1129. sides. The Django developers believe this is a violation of the DRY (Don't
  1130. Repeat Yourself) principle, so Django only requires you to define the
  1131. relationship on one end.
  1132. But how is this possible, given that a model class doesn't know which other
  1133. model classes are related to it until those other model classes are loaded?
  1134. The answer lies in the :data:`app registry <django.apps.apps>`. When Django
  1135. starts, it imports each application listed in :setting:`INSTALLED_APPS`, and
  1136. then the ``models`` module inside each application. Whenever a new model class
  1137. is created, Django adds backward-relationships to any related models. If the
  1138. related models haven't been imported yet, Django keeps tracks of the
  1139. relationships and adds them when the related models eventually are imported.
  1140. For this reason, it's particularly important that all the models you're using
  1141. be defined in applications listed in :setting:`INSTALLED_APPS`. Otherwise,
  1142. backwards relations may not work properly.
  1143. Queries over related objects
  1144. ----------------------------
  1145. Queries involving related objects follow the same rules as queries involving
  1146. normal value fields. When specifying the value for a query to match, you may
  1147. use either an object instance itself, or the primary key value for the object.
  1148. For example, if you have a Blog object ``b`` with ``id=5``, the following
  1149. three queries would be identical::
  1150. Entry.objects.filter(blog=b) # Query using object instance
  1151. Entry.objects.filter(blog=b.id) # Query using id from instance
  1152. Entry.objects.filter(blog=5) # Query using id directly
  1153. Falling back to raw SQL
  1154. =======================
  1155. If you find yourself needing to write an SQL query that is too complex for
  1156. Django's database-mapper to handle, you can fall back on writing SQL by hand.
  1157. Django has a couple of options for writing raw SQL queries; see
  1158. :doc:`/topics/db/sql`.
  1159. Finally, it's important to note that the Django database layer is merely an
  1160. interface to your database. You can access your database via other tools,
  1161. programming languages or database frameworks; there's nothing Django-specific
  1162. about your database.