queries.txt 52 KB

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