queries.txt 38 KB

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