queries.txt 51 KB

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