queries.txt 49 KB

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