queries.txt 44 KB

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