queries.txt 41 KB

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