queries.txt 41 KB

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