queries.txt 50 KB

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