queries.txt 49 KB

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