queries.txt 51 KB

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