queries.txt 49 KB

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