queries.txt 49 KB

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