TEXT 30
Queries.txt Guest on 29th April 2021 06:43:49 AM
  1. ==============
  2. Making queries
  3. ==============
  4.  
  5. .. currentmodule:: django.db.models
  6.  
  7. Once you've created your :doc:`data models </topics/db/models>`, Django
  8. automatically gives you a database-abstraction API that lets you create,
  9. retrieve, update and delete objects. This document explains how to use this
  10. API. Refer to the :doc:`data model reference </ref/models/index>` for full
  11. details of all the various model lookup options.
  12.  
  13. Throughout this guide (and in the reference), we'll refer to the following
  14. models, which comprise a Weblog application:
  15.  
  16. .. _queryset-model-example:
  17.  
  18. .. code-block:: python
  19.  
  20.     from django.db import models
  21.  
  22.     class Blog(models.Model):
  23.         name = models.CharField(max_length=100)
  24.         tagline = models.TextField()
  25.  
  26.         def __str__(self):              # __unicode__ on Python 2
  27.             return self.name
  28.  
  29.     class Author(models.Model):
  30.         name = models.CharField(max_length=50)
  31.         email = models.EmailField()
  32.  
  33.         def __str__(self):              # __unicode__ on Python 2
  34.             return self.name
  35.  
  36.     class Entry(models.Model):
  37.         blog = models.ForeignKey(Blog)
  38.         headline = models.CharField(max_length=255)
  39.         body_text = models.TextField()
  40.         pub_date = models.DateField()
  41.         mod_date = models.DateField()
  42.         authors = models.ManyToManyField(Author)
  43.         n_comments = models.IntegerField()
  44.         n_pingbacks = models.IntegerField()
  45.         rating = models.IntegerField()
  46.  
  47.         def __str__(self):              # __unicode__ on Python 2
  48.             return self.headline
  49.  
  50. Creating objects
  51. ================
  52.  
  53. To represent database-table data in Python objects, Django uses an intuitive
  54. system: A model class represents a database table, and an instance of that
  55. class represents a particular record in the database table.
  56.  
  57. To create an object, instantiate it using keyword arguments to the model class,
  58. then call :meth:`~django.db.models.Model.save` to save it to the database.
  59.  
  60. Assuming models live in a file ``mysite/blog/models.py``, here's an example::
  61.  
  62.     >>> from blog.models import Blog
  63.     >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
  64.     >>> b.save()
  65.  
  66. This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
  67. the database until you explicitly call :meth:`~django.db.models.Model.save`.
  68.  
  69. The :meth:`~django.db.models.Model.save` method has no return value.
  70.  
  71. .. seealso::
  72.  
  73.     :meth:`~django.db.models.Model.save` takes a number of advanced options not
  74.     described here. See the documentation for
  75.     :meth:`~django.db.models.Model.save` for complete details.
  76.  
  77.     To create and save an object in a single step, use the
  78.     :meth:`~django.db.models.query.QuerySet.create()` method.
  79.  
  80. Saving changes to objects
  81. =========================
  82.  
  83. To save changes to an object that's already in the database, use
  84. :meth:`~django.db.models.Model.save`.
  85.  
  86. Given a ``Blog`` instance ``b5`` that has already been saved to the database,
  87. this example changes its name and updates its record in the database::
  88.  
  89.     >>> b5.name = 'New name'
  90.     >>> b5.save()
  91.  
  92. This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
  93. the database until you explicitly call :meth:`~django.db.models.Model.save`.
  94.  
  95. Saving ``ForeignKey`` and ``ManyToManyField`` fields
  96. ----------------------------------------------------
  97.  
  98. Updating a :class:`~django.db.models.ForeignKey` field works exactly the same
  99. way as saving a normal field -- simply assign an object of the right type to
  100. the field in question. This example updates the ``blog`` attribute of an
  101. ``Entry`` instance ``entry``, assuming appropriate instances of ``Entry`` and
  102. ``Blog`` are already saved to the database (so we can retrieve them below)::
  103.  
  104.     >>> from blog.models import Entry
  105.     >>> entry = Entry.objects.get(pk=1)
  106.     >>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
  107.     >>> entry.blog = cheese_blog
  108.     >>> entry.save()
  109.  
  110. Updating a :class:`~django.db.models.ManyToManyField` works a little
  111. differently -- use the
  112. :meth:`~django.db.models.fields.related.RelatedManager.add` method on the field
  113. to add a record to the relation. This example adds the ``Author`` instance
  114. ``joe`` to the ``entry`` object::
  115.  
  116.     >>> from blog.models import Author
  117.     >>> joe = Author.objects.create(name="Joe")
  118.     >>> entry.authors.add(joe)
  119.  
  120. To add multiple records to a :class:`~django.db.models.ManyToManyField` in one
  121. go, include multiple arguments in the call to
  122. :meth:`~django.db.models.fields.related.RelatedManager.add`, like this::
  123.  
  124.     >>> john = Author.objects.create(name="John")
  125.     >>> paul = Author.objects.create(name="Paul")
  126.     >>> george = Author.objects.create(name="George")
  127.     >>> ringo = Author.objects.create(name="Ringo")
  128.     >>> entry.authors.add(john, paul, george, ringo)
  129.  
  130. Django will complain if you try to assign or add an object of the wrong type.
  131.  
  132. .. _retrieving-objects:
  133.  
  134. Retrieving objects
  135. ==================
  136.  
  137. To retrieve objects from your database, construct a
  138. :class:`~django.db.models.query.QuerySet` via a
  139. :class:`~django.db.models.Manager` on your model class.
  140.  
  141. A :class:`~django.db.models.query.QuerySet` represents a collection of objects
  142. from your database. It can have zero, one or many *filters*. Filters narrow
  143. down the query results based on the given parameters. In SQL terms, a
  144. :class:`~django.db.models.query.QuerySet` equates to a ``SELECT`` statement,
  145. and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
  146.  
  147. You get a :class:`~django.db.models.query.QuerySet` by using your model's
  148. :class:`~django.db.models.Manager`. Each model has at least one
  149. :class:`~django.db.models.Manager`, and it's called
  150. :attr:`~django.db.models.Model.objects` by default. Access it directly via the
  151. model class, like so::
  152.  
  153.     >>> Blog.objects
  154.     <django.db.models.manager.Manager object at ...>
  155.     >>> b = Blog(name='Foo', tagline='Bar')
  156.     >>> b.objects
  157.     Traceback:
  158.         ...
  159.     AttributeError: "Manager isn't accessible via Blog instances."
  160.  
  161. .. note::
  162.  
  163.     ``Managers`` are accessible only via model classes, rather than from model
  164.     instances, to enforce a separation between "table-level" operations and
  165.     "record-level" operations.
  166.  
  167. The :class:`~django.db.models.Manager` is the main source of ``QuerySets`` for
  168. a model. For example, ``Blog.objects.all()`` returns a
  169. :class:`~django.db.models.query.QuerySet` that contains all ``Blog`` objects in
  170. the database.
  171.  
  172. Retrieving all objects
  173. ----------------------
  174.  
  175. The simplest way to retrieve objects from a table is to get all of them. To do
  176. this, use the :meth:`~django.db.models.query.QuerySet.all` method on a
  177. :class:`~django.db.models.Manager`::
  178.  
  179.     >>> all_entries = Entry.objects.all()
  180.  
  181. The :meth:`~django.db.models.query.QuerySet.all` method returns a
  182. :class:`~django.db.models.query.QuerySet` of all the objects in the database.
  183.  
  184. Retrieving specific objects with filters
  185. ----------------------------------------
  186.  
  187. The :class:`~django.db.models.query.QuerySet` returned by
  188. :meth:`~django.db.models.query.QuerySet.all` describes all objects in the
  189. database table. Usually, though, you'll need to select only a subset of the
  190. complete set of objects.
  191.  
  192. To create such a subset, you refine the initial
  193. :class:`~django.db.models.query.QuerySet`, adding filter conditions. The two
  194. most common ways to refine a :class:`~django.db.models.query.QuerySet` are:
  195.  
  196. ``filter(**kwargs)``
  197.     Returns a new :class:`~django.db.models.query.QuerySet` containing objects
  198.     that match the given lookup parameters.
  199.  
  200. ``exclude(**kwargs)``
  201.     Returns a new :class:`~django.db.models.query.QuerySet` containing objects
  202.     that do *not* match the given lookup parameters.
  203.  
  204. The lookup parameters (``**kwargs`` in the above function definitions) should
  205. be in the format described in `Field lookups`_ below.
  206.  
  207. For example, to get a :class:`~django.db.models.query.QuerySet` of blog entries
  208. from the year 2006, use :meth:`~django.db.models.query.QuerySet.filter` like
  209. so::
  210.  
  211.     Entry.objects.filter(pub_date__year=2006)
  212.  
  213. With the default manager class, it is the same as::
  214.  
  215.     Entry.objects.all().filter(pub_date__year=2006)
  216.  
  217. .. _chaining-filters:
  218.  
  219. Chaining filters
  220. ~~~~~~~~~~~~~~~~
  221.  
  222. The result of refining a :class:`~django.db.models.query.QuerySet` is itself a
  223. :class:`~django.db.models.query.QuerySet`, so it's possible to chain
  224. refinements together. For example::
  225.  
  226.     >>> Entry.objects.filter(
  227.     ...     headline__startswith='What'
  228.     ... ).exclude(
  229.     ...     pub_date__gte=datetime.date.today()
  230.     ... ).filter(
  231.     ...     pub_date__gte=datetime(2005, 1, 30)
  232.     ... )
  233.  
  234. This takes the initial :class:`~django.db.models.query.QuerySet` of all entries
  235. in the database, adds a filter, then an exclusion, then another filter. The
  236. final result is a :class:`~django.db.models.query.QuerySet` containing all
  237. entries with a headline that starts with "What", that were published between
  238. January 30, 2005, and the current day.
  239.  
  240. .. _filtered-querysets-are-unique:
  241.  
  242. Filtered QuerySets are unique
  243. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  244.  
  245. Each time you refine a :class:`~django.db.models.query.QuerySet`, you get a
  246. brand-new :class:`~django.db.models.query.QuerySet` that is in no way bound to
  247. the previous :class:`~django.db.models.query.QuerySet`. Each refinement creates
  248. a separate and distinct :class:`~django.db.models.query.QuerySet` that can be
  249. stored, used and reused.
  250.  
  251. Example::
  252.  
  253.     >>> q1 = Entry.objects.filter(headline__startswith="What")
  254.     >>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
  255.     >>> q3 = q1.filter(pub_date__gte=datetime.date.today())
  256.  
  257. These three ``QuerySets`` are separate. The first is a base
  258. :class:`~django.db.models.query.QuerySet` containing all entries that contain a
  259. headline starting with "What". The second is a subset of the first, with an
  260. additional criteria that excludes records whose ``pub_date`` is today or in the
  261. future. The third is a subset of the first, with an additional criteria that
  262. selects only the records whose ``pub_date`` is today or in the future. The
  263. initial :class:`~django.db.models.query.QuerySet` (``q1``) is unaffected by the
  264. refinement process.
  265.  
  266. .. _querysets-are-lazy:
  267.  
  268. QuerySets are lazy
  269. ~~~~~~~~~~~~~~~~~~
  270.  
  271. ``QuerySets`` are lazy -- the act of creating a
  272. :class:`~django.db.models.query.QuerySet` doesn't involve any database
  273. activity. You can stack filters together all day long, and Django won't
  274. actually run the query until the :class:`~django.db.models.query.QuerySet` is
  275. *evaluated*. Take a look at this example::
  276.  
  277.     >>> q = Entry.objects.filter(headline__startswith="What")
  278.     >>> q = q.filter(pub_date__lte=datetime.date.today())
  279.     >>> q = q.exclude(body_text__icontains="food")
  280.     >>> print(q)
  281.  
  282. Though this looks like three database hits, in fact it hits the database only
  283. once, at the last line (``print(q)``). In general, the results of a
  284. :class:`~django.db.models.query.QuerySet` aren't fetched from the database
  285. until you "ask" for them. When you do, the
  286. :class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the
  287. database. For more details on exactly when evaluation takes place, see
  288. :ref:`when-querysets-are-evaluated`.
  289.  
  290.  
  291. .. _retrieving-single-object-with-get:
  292.  
  293. Retrieving a single object with get
  294. -----------------------------------
  295.  
  296. :meth:`~django.db.models.query.QuerySet.filter` will always give you a
  297. :class:`~django.db.models.query.QuerySet`, even if only a single object matches
  298. the query - in this case, it will be a
  299. :class:`~django.db.models.query.QuerySet` containing a single element.
  300.  
  301. If you know there is only one object that matches your query, you can use the
  302. :meth:`~django.db.models.query.QuerySet.get` method on a
  303. :class:`~django.db.models.Manager` which returns the object directly::
  304.  
  305.     >>> one_entry = Entry.objects.get(pk=1)
  306.  
  307. You can use any query expression with
  308. :meth:`~django.db.models.query.QuerySet.get`, just like with
  309. :meth:`~django.db.models.query.QuerySet.filter` - again, see `Field lookups`_
  310. below.
  311.  
  312. Note that there is a difference between using
  313. :meth:`~django.db.models.query.QuerySet.get`, and using
  314. :meth:`~django.db.models.query.QuerySet.filter` with a slice of ``[0]``. If
  315. there are no results that match the query,
  316. :meth:`~django.db.models.query.QuerySet.get` will raise a ``DoesNotExist``
  317. exception. This exception is an attribute of the model class that the query is
  318. being performed on - so in the code above, if there is no ``Entry`` object with
  319. a primary key of 1, Django will raise ``Entry.DoesNotExist``.
  320.  
  321. Similarly, Django will complain if more than one item matches the
  322. :meth:`~django.db.models.query.QuerySet.get` query. In this case, it will raise
  323. :exc:`~django.core.exceptions.MultipleObjectsReturned`, which again is an
  324. attribute of the model class itself.
  325.  
  326.  
  327. Other QuerySet methods
  328. ----------------------
  329.  
  330. Most of the time you'll use :meth:`~django.db.models.query.QuerySet.all`,
  331. :meth:`~django.db.models.query.QuerySet.get`,
  332. :meth:`~django.db.models.query.QuerySet.filter` and
  333. :meth:`~django.db.models.query.QuerySet.exclude` when you need to look up
  334. objects from the database. However, that's far from all there is; see the
  335. :ref:`QuerySet API Reference <queryset-api>` for a complete list of all the
  336. various :class:`~django.db.models.query.QuerySet` methods.
  337.  
  338. .. _limiting-querysets:
  339.  
  340. Limiting QuerySets
  341. ------------------
  342.  
  343. Use a subset of Python's array-slicing syntax to limit your
  344. :class:`~django.db.models.query.QuerySet` to a certain number of results. This
  345. is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
  346.  
  347. For example, this returns the first 5 objects (``LIMIT 5``)::
  348.  
  349.     >>> Entry.objects.all()[:5]
  350.  
  351. This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
  352.  
  353.     >>> Entry.objects.all()[5:10]
  354.  
  355. Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported.
  356.  
  357. Generally, slicing a :class:`~django.db.models.query.QuerySet` returns a new
  358. :class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An
  359. exception is if you use the "step" parameter of Python slice syntax. For
  360. example, this would actually execute the query in order to return a list of
  361. every *second* object of the first 10::
  362.  
  363.     >>> Entry.objects.all()[:10:2]
  364.  
  365. To retrieve a *single* object rather than a list
  366. (e.g. ``SELECT foo FROM bar LIMIT 1``), use a simple index instead of a
  367. slice. For example, this returns the first ``Entry`` in the database, after
  368. ordering entries alphabetically by headline::
  369.  
  370.     >>> Entry.objects.order_by('headline')[0]
  371.  
  372. This is roughly equivalent to::
  373.  
  374.     >>> Entry.objects.order_by('headline')[0:1].get()
  375.  
  376. Note, however, that the first of these will raise ``IndexError`` while the
  377. second will raise ``DoesNotExist`` if no objects match the given criteria. See
  378. :meth:`~django.db.models.query.QuerySet.get` for more details.
  379.  
  380. .. _field-lookups-intro:
  381.  
  382. Field lookups
  383. -------------
  384.  
  385. Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
  386. specified as keyword arguments to the :class:`~django.db.models.query.QuerySet`
  387. methods :meth:`~django.db.models.query.QuerySet.filter`,
  388. :meth:`~django.db.models.query.QuerySet.exclude` and
  389. :meth:`~django.db.models.query.QuerySet.get`.
  390.  
  391. Basic lookups keyword arguments take the form ``field__lookuptype=value``.
  392. (That's a double-underscore). For example::
  393.  
  394.     >>> Entry.objects.filter(pub_date__lte='2006-01-01')
  395.  
  396. translates (roughly) into the following SQL:
  397.  
  398. .. code-block:: sql
  399.  
  400.     SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
  401.  
  402. .. admonition:: How this is possible
  403.  
  404.    Python has the ability to define functions that accept arbitrary name-value
  405.    arguments whose names and values are evaluated at runtime. For more
  406.    information, see `Keyword Arguments`_ in the official Python tutorial.
  407.  
  408.    .. _`Keyword Arguments`: https://docs.python.org/tutorial/controlflow.html#keyword-arguments
  409.  
  410. The field specified in a lookup has to be the name of a model field. There's
  411. one exception though, in case of a :class:`~django.db.models.ForeignKey` you
  412. can specify the field name suffixed with ``_id``. In this case, the value
  413. parameter is expected to contain the raw value of the foreign model's primary
  414. key. For example:
  415.  
  416.     >>> Entry.objects.filter(blog_id=4)
  417.  
  418. If you pass an invalid keyword argument, a lookup function will raise
  419. ``TypeError``.
  420.  
  421. The database API supports about two dozen lookup types; a complete reference
  422. can be found in the :ref:`field lookup reference <field-lookups>`. To give you
  423. a taste of what's available, here's some of the more common lookups you'll
  424. probably use:
  425.  
  426. :lookup:`exact`
  427.     An "exact" match. For example::
  428.  
  429.         >>> Entry.objects.get(headline__exact="Man bites dog")
  430.  
  431.     Would generate SQL along these lines:
  432.  
  433.     .. code-block:: sql
  434.  
  435.         SELECT ... WHERE headline = 'Man bites dog';
  436.  
  437.     If you don't provide a lookup type -- that is, if your keyword argument
  438.     doesn't contain a double underscore -- the lookup type is assumed to be
  439.     ``exact``.
  440.  
  441.     For example, the following two statements are equivalent::
  442.  
  443.         >>> Blog.objects.get(id__exact=14)  # Explicit form
  444.         >>> Blog.objects.get(id=14)         # __exact is implied
  445.  
  446.     This is for convenience, because ``exact`` lookups are the common case.
  447.  
  448. :lookup:`iexact`
  449.     A case-insensitive match. So, the query::
  450.  
  451.         >>> Blog.objects.get(name__iexact="beatles blog")
  452.  
  453.     Would match a ``Blog`` titled ``"Beatles Blog"``, ``"beatles blog"``, or
  454.     even ``"BeAtlES blOG"``.
  455.  
  456. :lookup:`contains`
  457.     Case-sensitive containment test. For example::
  458.  
  459.         Entry.objects.get(headline__contains='Lennon')
  460.  
  461.     Roughly translates to this SQL:
  462.  
  463.     .. code-block:: sql
  464.  
  465.         SELECT ... WHERE headline LIKE '%Lennon%';
  466.  
  467.     Note this will match the headline ``'Today Lennon honored'`` but not
  468.     ``'today lennon honored'``.
  469.  
  470.     There's also a case-insensitive version, :lookup:`icontains`.
  471.  
  472. :lookup:`startswith`, :lookup:`endswith`
  473.     Starts-with and ends-with search, respectively. There are also
  474.     case-insensitive versions called :lookup:`istartswith` and
  475.     :lookup:`iendswith`.
  476.  
  477. Again, this only scratches the surface. A complete reference can be found in the
  478. :ref:`field lookup reference <field-lookups>`.
  479.  
  480. .. _lookups-that-span-relationships:
  481.  
  482. Lookups that span relationships
  483. -------------------------------
  484.  
  485. Django offers a powerful and intuitive way to "follow" relationships in
  486. lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
  487. scenes. To span a relationship, just use the field name of related fields
  488. across models, separated by double underscores, until you get to the field you
  489. want.
  490.  
  491. This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
  492. is ``'Beatles Blog'``::
  493.  
  494.     >>> Entry.objects.filter(blog__name='Beatles Blog')
  495.  
  496. This spanning can be as deep as you'd like.
  497.  
  498. It works backwards, too. To refer to a "reverse" relationship, just use the
  499. lowercase name of the model.
  500.  
  501. This example retrieves all ``Blog`` objects which have at least one ``Entry``
  502. whose ``headline`` contains ``'Lennon'``::
  503.  
  504.     >>> Blog.objects.filter(entry__headline__contains='Lennon')
  505.  
  506. If you are filtering across multiple relationships and one of the intermediate
  507. models doesn't have a value that meets the filter condition, Django will treat
  508. it as if there is an empty (all values are ``NULL``), but valid, object there.
  509. All this means is that no error will be raised. For example, in this filter::
  510.  
  511.     Blog.objects.filter(entry__authors__name='Lennon')
  512.  
  513. (if there was a related ``Author`` model), if there was no ``author``
  514. associated with an entry, it would be treated as if there was also no ``name``
  515. attached, rather than raising an error because of the missing ``author``.
  516. Usually this is exactly what you want to have happen. The only case where it
  517. might be confusing is if you are using :lookup:`isnull`. Thus::
  518.  
  519.     Blog.objects.filter(entry__authors__name__isnull=True)
  520.  
  521. will return ``Blog`` objects that have an empty ``name`` on the ``author`` and
  522. also those which have an empty ``author`` on the ``entry``. If you don't want
  523. those latter objects, you could write::
  524.  
  525.     Blog.objects.filter(entry__authors__isnull=False,
  526.             entry__authors__name__isnull=True)
  527.  
  528. Spanning multi-valued relationships
  529. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  530.  
  531. When you are filtering an object based on a
  532. :class:`~django.db.models.ManyToManyField` or a reverse
  533. :class:`~django.db.models.ForeignKey`, there are two different sorts of filter
  534. you may be interested in. Consider the ``Blog``/``Entry`` relationship
  535. (``Blog`` to ``Entry`` is a one-to-many relation). We might be interested in
  536. finding blogs that have an entry which has both *"Lennon"* in the headline and
  537. was published in 2008. Or we might want to find blogs that have an entry with
  538. *"Lennon"* in the headline as well as an entry that was published
  539. in 2008. Since there are multiple entries associated with a single ``Blog``,
  540. both of these queries are possible and make sense in some situations.
  541.  
  542. The same type of situation arises with a
  543. :class:`~django.db.models.ManyToManyField`. For example, if an ``Entry`` has a
  544. :class:`~django.db.models.ManyToManyField` called ``tags``, we might want to
  545. find entries linked to tags called *"music"* and *"bands"* or we might want an
  546. entry that contains a tag with a name of *"music"* and a status of *"public"*.
  547.  
  548. To handle both of these situations, Django has a consistent way of processing
  549. :meth:`~django.db.models.query.QuerySet.filter` calls. Everything inside a
  550. single :meth:`~django.db.models.query.QuerySet.filter` call is applied
  551. simultaneously to filter out items matching all those requirements. Successive
  552. :meth:`~django.db.models.query.QuerySet.filter` calls further restrict the set
  553. of objects, but for multi-valued relations, they apply to any object linked to
  554. the primary model, not necessarily those objects that were selected by an
  555. earlier :meth:`~django.db.models.query.QuerySet.filter` call.
  556.  
  557. That may sound a bit confusing, so hopefully an example will clarify. To
  558. select all blogs that contain entries with both *"Lennon"* in the headline
  559. and that were published in 2008 (the same entry satisfying both conditions),
  560. we would write::
  561.  
  562.     Blog.objects.filter(entry__headline__contains='Lennon',
  563.             entry__pub_date__year=2008)
  564.  
  565. To select all blogs that contain an entry with *"Lennon"* in the headline
  566. **as well as** an entry that was published in 2008, we would write::
  567.  
  568.     Blog.objects.filter(entry__headline__contains='Lennon').filter(
  569.             entry__pub_date__year=2008)
  570.  
  571. Suppose there is only one blog that had both entries containing *"Lennon"* and
  572. entries from 2008, but that none of the entries from 2008 contained *"Lennon"*.
  573. The first query would not return any blogs, but the second query would return
  574. that one blog.
  575.  
  576. In the second example, the first filter restricts the queryset to all those
  577. blogs linked to entries with *"Lennon"* in the headline. The second filter
  578. restricts the set of blogs *further* to those that are also linked to entries
  579. that were published in 2008. The entries selected by the second filter may or
  580. may not be the same as the entries in the first filter. We are filtering the
  581. ``Blog`` items with each filter statement, not the ``Entry`` items.
  582.  
  583. .. note::
  584.  
  585.     The behavior of :meth:`~django.db.models.query.QuerySet.filter` for queries
  586.     that span multi-value relationships, as described above, is not implemented
  587.     equivalently for :meth:`~django.db.models.query.QuerySet.exclude`. Instead,
  588.     the conditions in a single :meth:`~django.db.models.query.QuerySet.exclude`
  589.     call will not necessarily refer to the same item.
  590.  
  591.     For example, the following query would exclude blogs that contain *both*
  592.     entries with *"Lennon"* in the headline *and* entries published in 2008::
  593.  
  594.         Blog.objects.exclude(
  595.             entry__headline__contains='Lennon',
  596.             entry__pub_date__year=2008,
  597.         )
  598.  
  599.     However, unlike the behavior when using
  600.     :meth:`~django.db.models.query.QuerySet.filter`, this will not limit blogs
  601.     based on entries that satisfy both conditions. In order to do that, i.e.
  602.     to select all blogs that do not contain entries published with *"Lennon"*
  603.     that were published in 2008, you need to make two queries::
  604.  
  605.         Blog.objects.exclude(
  606.             entry=Entry.objects.filter(
  607.                 headline__contains='Lennon',
  608.                 pub_date__year=2008,
  609.             ),
  610.         )
  611.  
  612. .. _using-f-expressions-in-filters:
  613.  
  614. Filters can reference fields on the model
  615. -----------------------------------------
  616.  
  617. In the examples given so far, we have constructed filters that compare
  618. the value of a model field with a constant. But what if you want to compare
  619. the value of a model field with another field on the same model?
  620.  
  621. Django provides :class:`F expressions <django.db.models.F>` to allow such
  622. comparisons. Instances of ``F()`` act as a reference to a model field within a
  623. query. These references can then be used in query filters to compare the values
  624. of two different fields on the same model instance.
  625.  
  626. For example, to find a list of all blog entries that have had more comments
  627. than pingbacks, we construct an ``F()`` object to reference the pingback count,
  628. and use that ``F()`` object in the query::
  629.  
  630.     >>> from django.db.models import F
  631.     >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
  632.  
  633. Django supports the use of addition, subtraction, multiplication,
  634. division, modulo, and power arithmetic with ``F()`` objects, both with constants
  635. and with other ``F()`` objects. To find all the blog entries with more than
  636. *twice* as many comments as pingbacks, we modify the query::
  637.  
  638.     >>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)
  639.  
  640. .. versionadded:: 1.7
  641.  
  642.     The power operator ``**`` was added.
  643.  
  644. To find all the entries where the rating of the entry is less than the
  645. sum of the pingback count and comment count, we would issue the
  646. query::
  647.  
  648.     >>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
  649.  
  650. You can also use the double underscore notation to span relationships in
  651. an ``F()`` object. An ``F()`` object with a double underscore will introduce
  652. any joins needed to access the related object. For example, to retrieve all
  653. the entries where the author's name is the same as the blog name, we could
  654. issue the query::
  655.  
  656.     >>> Entry.objects.filter(authors__name=F('blog__name'))
  657.  
  658. For date and date/time fields, you can add or subtract a
  659. :class:`~datetime.timedelta` object. The following would return all entries
  660. that were modified more than 3 days after they were published::
  661.  
  662.     >>> from datetime import timedelta
  663.     >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
  664.  
  665. The ``F()`` objects support bitwise operations by ``.bitand()`` and
  666. ``.bitor()``, for example::
  667.  
  668.     >>> F('somefield').bitand(16)
  669.  
  670. The pk lookup shortcut
  671. ----------------------
  672.  
  673. For convenience, Django provides a ``pk`` lookup shortcut, which stands for
  674. "primary key".
  675.  
  676. In the example ``Blog`` model, the primary key is the ``id`` field, so these
  677. three statements are equivalent::
  678.  
  679.     >>> Blog.objects.get(id__exact=14) # Explicit form
  680.     >>> Blog.objects.get(id=14) # __exact is implied
  681.     >>> Blog.objects.get(pk=14) # pk implies id__exact
  682.  
  683. The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
  684. can be combined with ``pk`` to perform a query on the primary key of a model::
  685.  
  686.     # Get blogs entries with id 1, 4 and 7
  687.     >>> Blog.objects.filter(pk__in=[1,4,7])
  688.  
  689.     # Get all blog entries with id > 14
  690.     >>> Blog.objects.filter(pk__gt=14)
  691.  
  692. ``pk`` lookups also work across joins. For example, these three statements are
  693. equivalent::
  694.  
  695.     >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
  696.     >>> Entry.objects.filter(blog__id=3)        # __exact is implied
  697.     >>> Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact
  698.  
  699. Escaping percent signs and underscores in LIKE statements
  700. ---------------------------------------------------------
  701.  
  702. The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
  703. ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
  704. and ``iendswith``) will automatically escape the two special characters used in
  705. ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
  706. statement, the percent sign signifies a multiple-character wildcard and the
  707. underscore signifies a single-character wildcard.)
  708.  
  709. This means things should work intuitively, so the abstraction doesn't leak.
  710. For example, to retrieve all the entries that contain a percent sign, just use
  711. the percent sign as any other character::
  712.  
  713.     >>> Entry.objects.filter(headline__contains='%')
  714.  
  715. Django takes care of the quoting for you; the resulting SQL will look something
  716. like this:
  717.  
  718. .. code-block:: sql
  719.  
  720.     SELECT ... WHERE headline LIKE '%\%%';
  721.  
  722. Same goes for underscores. Both percentage signs and underscores are handled
  723. for you transparently.
  724.  
  725. .. _caching-and-querysets:
  726.  
  727. Caching and QuerySets
  728. ---------------------
  729.  
  730. Each :class:`~django.db.models.query.QuerySet` contains a cache to minimize
  731. database access. Understanding how it works will allow you to write the most
  732. efficient code.
  733.  
  734. In a newly created :class:`~django.db.models.query.QuerySet`, the cache is
  735. empty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated
  736. -- and, hence, a database query happens -- Django saves the query results in
  737. the :class:`~django.db.models.query.QuerySet`’s cache and returns the results
  738. that have been explicitly requested (e.g., the next element, if the
  739. :class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent
  740. evaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached
  741. results.
  742.  
  743. Keep this caching behavior in mind, because it may bite you if you don't use
  744. your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
  745. following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
  746. them, and throw them away::
  747.  
  748.     >>> print([e.headline for e in Entry.objects.all()])
  749.     >>> print([e.pub_date for e in Entry.objects.all()])
  750.  
  751. That means the same database query will be executed twice, effectively doubling
  752. your database load. Also, there's a possibility the two lists may not include
  753. the same database records, because an ``Entry`` may have been added or deleted
  754. in the split second between the two requests.
  755.  
  756. To avoid this problem, simply save the
  757. :class:`~django.db.models.query.QuerySet` and reuse it::
  758.  
  759.     >>> queryset = Entry.objects.all()
  760.     >>> print([p.headline for p in queryset]) # Evaluate the query set.
  761.     >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
  762.  
  763. When querysets are not cached
  764. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  765.  
  766. Querysets do not always cache their results.  When evaluating only *part* of
  767. the queryset, the cache is checked, but if it is not populated then the items
  768. returned by the subsequent query are not cached. Specifically, this means that
  769. :ref:`limiting the queryset <limiting-querysets>` using an array slice or an
  770. index will not populate the cache.
  771.  
  772. For example, repeatedly getting a certain index in a queryset object will query
  773. the database each time::
  774.  
  775.     >>> queryset = Entry.objects.all()
  776.     >>> print queryset[5] # Queries the database
  777.     >>> print queryset[5] # Queries the database again
  778.  
  779. However, if the entire queryset has already been evaluated, the cache will be
  780. checked instead::
  781.  
  782.     >>> queryset = Entry.objects.all()
  783.     >>> [entry for entry in queryset] # Queries the database
  784.     >>> print queryset[5] # Uses cache
  785.     >>> print queryset[5] # Uses cache
  786.  
  787. Here are some examples of other actions that will result in the entire queryset
  788. being evaluated and therefore populate the cache::
  789.  
  790.     >>> [entry for entry in queryset]
  791.     >>> bool(queryset)
  792.     >>> entry in queryset
  793.     >>> list(queryset)
  794.  
  795. .. note::
  796.  
  797.     Simply printing the queryset will not populate the cache. This is because
  798.     the call to ``__repr__()`` only returns a slice of the entire queryset.
  799.  
  800. .. _complex-lookups-with-q:
  801.  
  802. Complex lookups with Q objects
  803. ==============================
  804.  
  805. Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
  806. etc. -- are "AND"ed together. If you need to execute more complex queries (for
  807. example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.
  808.  
  809. A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object
  810. used to encapsulate a collection of keyword arguments. These keyword arguments
  811. are specified as in "Field lookups" above.
  812.  
  813. For example, this ``Q`` object encapsulates a single ``LIKE`` query::
  814.  
  815.     from django.db.models import Q
  816.     Q(question__startswith='What')
  817.  
  818. ``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
  819. operator is used on two ``Q`` objects, it yields a new ``Q`` object.
  820.  
  821. For example, this statement yields a single ``Q`` object that represents the
  822. "OR" of two ``"question__startswith"`` queries::
  823.  
  824.     Q(question__startswith='Who') | Q(question__startswith='What')
  825.  
  826. This is equivalent to the following SQL ``WHERE`` clause::
  827.  
  828.     WHERE question LIKE 'Who%' OR question LIKE 'What%'
  829.  
  830. You can compose statements of arbitrary complexity by combining ``Q`` objects
  831. with the ``&`` and ``|`` operators and use parenthetical grouping. Also, ``Q``
  832. objects can be negated using the ``~`` operator, allowing for combined lookups
  833. that combine both a normal query and a negated (``NOT``) query::
  834.  
  835.     Q(question__startswith='Who') | ~Q(pub_date__year=2005)
  836.  
  837. Each lookup function that takes keyword-arguments
  838. (e.g. :meth:`~django.db.models.query.QuerySet.filter`,
  839. :meth:`~django.db.models.query.QuerySet.exclude`,
  840. :meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more
  841. ``Q`` objects as positional (not-named) arguments. If you provide multiple
  842. ``Q`` object arguments to a lookup function, the arguments will be "AND"ed
  843. together. For example::
  844.  
  845.     Poll.objects.get(
  846.         Q(question__startswith='Who'),
  847.         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
  848.     )
  849.  
  850. ... roughly translates into the SQL::
  851.  
  852.     SELECT * from polls WHERE question LIKE 'Who%'
  853.         AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
  854.  
  855. Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
  856. arguments provided to a lookup function (be they keyword arguments or ``Q``
  857. objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
  858. precede the definition of any keyword arguments. For example::
  859.  
  860.     Poll.objects.get(
  861.         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
  862.         question__startswith='Who')
  863.  
  864. ... would be a valid query, equivalent to the previous example; but::
  865.  
  866.     # INVALID QUERY
  867.     Poll.objects.get(
  868.         question__startswith='Who',
  869.         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
  870.  
  871. ... would not be valid.
  872.  
  873. .. seealso::
  874.  
  875.     The `OR lookups examples`_ in the Django unit tests show some possible uses
  876.     of ``Q``.
  877.  
  878.     .. _OR lookups examples: https://github.com/django/django/blob/master/tests/or_lookups/tests.py
  879.  
  880. Comparing objects
  881. =================
  882.  
  883. To compare two model instances, just use the standard Python comparison operator,
  884. the double equals sign: ``==``. Behind the scenes, that compares the primary
  885. key values of two models.
  886.  
  887. Using the ``Entry`` example above, the following two statements are equivalent::
  888.  
  889.     >>> some_entry == other_entry
  890.     >>> some_entry.id == other_entry.id
  891.  
  892. If a model's primary key isn't called ``id``, no problem. Comparisons will
  893. always use the primary key, whatever it's called. For example, if a model's
  894. primary key field is called ``name``, these two statements are equivalent::
  895.  
  896.     >>> some_obj == other_obj
  897.     >>> some_obj.name == other_obj.name
  898.  
  899. .. _topics-db-queries-delete:
  900.  
  901. Deleting objects
  902. ================
  903.  
  904. The delete method, conveniently, is named
  905. :meth:`~django.db.models.Model.delete`. This method immediately deletes the
  906. object and has no return value. Example::
  907.  
  908.     e.delete()
  909.  
  910. You can also delete objects in bulk. Every
  911. :class:`~django.db.models.query.QuerySet` has a
  912. :meth:`~django.db.models.query.QuerySet.delete` method, which deletes all
  913. members of that :class:`~django.db.models.query.QuerySet`.
  914.  
  915. For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
  916. 2005::
  917.  
  918.     Entry.objects.filter(pub_date__year=2005).delete()
  919.  
  920. Keep in mind that this will, whenever possible, be executed purely in SQL, and
  921. so the ``delete()`` methods of individual object instances will not necessarily
  922. be called during the process. If you've provided a custom ``delete()`` method
  923. on a model class and want to ensure that it is called, you will need to
  924. "manually" delete instances of that model (e.g., by iterating over a
  925. :class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each
  926. object individually) rather than using the bulk
  927. :meth:`~django.db.models.query.QuerySet.delete` method of a
  928. :class:`~django.db.models.query.QuerySet`.
  929.  
  930. When Django deletes an object, by default it emulates the behavior of the SQL
  931. constraint ``ON DELETE CASCADE`` -- in other words, any objects which had
  932. foreign keys pointing at the object to be deleted will be deleted along with
  933. it. For example::
  934.  
  935.     b = Blog.objects.get(pk=1)
  936.     # This will delete the Blog and all of its Entry objects.
  937.     b.delete()
  938.  
  939. This cascade behavior is customizable via the
  940. :attr:`~django.db.models.ForeignKey.on_delete` argument to the
  941. :class:`~django.db.models.ForeignKey`.
  942.  
  943. Note that :meth:`~django.db.models.query.QuerySet.delete` is the only
  944. :class:`~django.db.models.query.QuerySet` method that is not exposed on a
  945. :class:`~django.db.models.Manager` itself. This is a safety mechanism to
  946. prevent you from accidentally requesting ``Entry.objects.delete()``, and
  947. deleting *all* the entries. If you *do* want to delete all the objects, then
  948. you have to explicitly request a complete query set::
  949.  
  950.     Entry.objects.all().delete()
  951.  
  952. .. _topics-db-queries-copy:
  953.  
  954. Copying model instances
  955. =======================
  956.  
  957. Although there is no built-in method for copying model instances, it is
  958. possible to easily create new instance with all fields' values copied. In the
  959. simplest case, you can just set ``pk`` to ``None``. Using our blog example::
  960.  
  961.     blog = Blog(name='My blog', tagline='Blogging is easy')
  962.     blog.save() # blog.pk == 1
  963.  
  964.     blog.pk = None
  965.     blog.save() # blog.pk == 2
  966.  
  967. Things get more complicated if you use inheritance. Consider a subclass of
  968. ``Blog``::
  969.  
  970.     class ThemeBlog(Blog):
  971.         theme = models.CharField(max_length=200)
  972.  
  973.     django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')
  974.     django_blog.save() # django_blog.pk == 3
  975.  
  976. Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::
  977.  
  978.     django_blog.pk = None
  979.     django_blog.id = None
  980.     django_blog.save() # django_blog.pk == 4
  981.  
  982. This process does not copy related objects. If you want to copy relations,
  983. you have to write a little bit more code. In our example, ``Entry`` has a many to many
  984. field to ``Author``::
  985.  
  986.     entry = Entry.objects.all()[0] # some previous entry
  987.     old_authors = entry.authors.all()
  988.     entry.pk = None
  989.     entry.save()
  990.     entry.authors = old_authors # saves new many2many relations
  991.  
  992. .. _topics-db-queries-update:
  993.  
  994. Updating multiple objects at once
  995. =================================
  996.  
  997. Sometimes you want to set a field to a particular value for all the objects in
  998. a :class:`~django.db.models.query.QuerySet`. You can do this with the
  999. :meth:`~django.db.models.query.QuerySet.update` method. For example::
  1000.  
  1001.     # Update all the headlines with pub_date in 2007.
  1002.     Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
  1003.  
  1004. You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
  1005. fields using this method. To update a non-relation field, provide the new value
  1006. as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
  1007. new value to be the new model instance you want to point to. For example::
  1008.  
  1009.     >>> b = Blog.objects.get(pk=1)
  1010.  
  1011.     # Change every Entry so that it belongs to this Blog.
  1012.     >>> Entry.objects.all().update(blog=b)
  1013.  
  1014. The ``update()`` method is applied instantly and returns the number of rows
  1015. matched by the query (which may not be equal to the number of rows updated if
  1016. some rows already have the new value). The only restriction on the
  1017. :class:`~django.db.models.query.QuerySet` that is updated is that it can only
  1018. access one database table, the model's main table. You can filter based on
  1019. related fields, but you can only update columns in the model's main
  1020. table. Example::
  1021.  
  1022.     >>> b = Blog.objects.get(pk=1)
  1023.  
  1024.     # Update all the headlines belonging to this Blog.
  1025.     >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
  1026.  
  1027. Be aware that the ``update()`` method is converted directly to an SQL
  1028. statement. It is a bulk operation for direct updates. It doesn't run any
  1029. :meth:`~django.db.models.Model.save` methods on your models, or emit the
  1030. ``pre_save`` or ``post_save`` signals (which are a consequence of calling
  1031. :meth:`~django.db.models.Model.save`), or honor the
  1032. :attr:`~django.db.models.DateField.auto_now` field option.
  1033. If you want to save every item in a :class:`~django.db.models.query.QuerySet`
  1034. and make sure that the :meth:`~django.db.models.Model.save` method is called on
  1035. each instance, you don't need any special function to handle that. Just loop
  1036. over them and call :meth:`~django.db.models.Model.save`::
  1037.  
  1038.     for item in my_queryset:
  1039.         item.save()
  1040.  
  1041. Calls to update can also use :class:`F expressions <django.db.models.F>` to
  1042. update one field based on the value of another field in the model. This is
  1043. especially useful for incrementing counters based upon their current value. For
  1044. example, to increment the pingback count for every entry in the blog::
  1045.  
  1046.     >>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
  1047.  
  1048. However, unlike ``F()`` objects in filter and exclude clauses, you can't
  1049. introduce joins when you use ``F()`` objects in an update -- you can only
  1050. reference fields local to the model being updated. If you attempt to introduce
  1051. a join with an ``F()`` object, a ``FieldError`` will be raised::
  1052.  
  1053.     # THIS WILL RAISE A FieldError
  1054.     >>> Entry.objects.update(headline=F('blog__name'))
  1055.  
  1056. .. _topics-db-queries-related:
  1057.  
  1058. Related objects
  1059. ===============
  1060.  
  1061. When you define a relationship in a model (i.e., a
  1062. :class:`~django.db.models.ForeignKey`,
  1063. :class:`~django.db.models.OneToOneField`, or
  1064. :class:`~django.db.models.ManyToManyField`), instances of that model will have
  1065. a convenient API to access the related object(s).
  1066.  
  1067. Using the models at the top of this page, for example, an ``Entry`` object ``e``
  1068. can get its associated ``Blog`` object by accessing the ``blog`` attribute:
  1069. ``e.blog``.
  1070.  
  1071. (Behind the scenes, this functionality is implemented by Python descriptors_.
  1072. This shouldn't really matter to you, but we point it out here for the curious.)
  1073.  
  1074. Django also creates API accessors for the "other" side of the relationship --
  1075. the link from the related model to the model that defines the relationship.
  1076. For example, a ``Blog`` object ``b`` has access to a list of all related
  1077. ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
  1078.  
  1079. All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
  1080. models defined at the top of this page.
  1081.  
  1082. .. _descriptors: http://users.rcn.com/python/download/Descriptor.htm
  1083.  
  1084. One-to-many relationships
  1085. -------------------------
  1086.  
  1087. Forward
  1088. ~~~~~~~
  1089.  
  1090. If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
  1091. will have access to the related (foreign) object via a simple attribute of the
  1092. model.
  1093.  
  1094. Example::
  1095.  
  1096.     >>> e = Entry.objects.get(id=2)
  1097.     >>> e.blog # Returns the related Blog object.
  1098.  
  1099. You can get and set via a foreign-key attribute. As you may expect, changes to
  1100. the foreign key aren't saved to the database until you call
  1101. :meth:`~django.db.models.Model.save`. Example::
  1102.  
  1103.     >>> e = Entry.objects.get(id=2)
  1104.     >>> e.blog = some_blog
  1105.     >>> e.save()
  1106.  
  1107. If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,
  1108. it allows ``NULL`` values), you can assign ``None`` to remove the relation.
  1109. Example::
  1110.  
  1111.     >>> e = Entry.objects.get(id=2)
  1112.     >>> e.blog = None
  1113.     >>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
  1114.  
  1115. Forward access to one-to-many relationships is cached the first time the
  1116. related object is accessed. Subsequent accesses to the foreign key on the same
  1117. object instance are cached. Example::
  1118.  
  1119.     >>> e = Entry.objects.get(id=2)
  1120.     >>> print(e.blog)  # Hits the database to retrieve the associated Blog.
  1121.     >>> print(e.blog)  # Doesn't hit the database; uses cached version.
  1122.  
  1123. Note that the :meth:`~django.db.models.query.QuerySet.select_related`
  1124. :class:`~django.db.models.query.QuerySet` method recursively prepopulates the
  1125. cache of all one-to-many relationships ahead of time. Example::
  1126.  
  1127.     >>> e = Entry.objects.select_related().get(id=2)
  1128.     >>> print(e.blog)  # Doesn't hit the database; uses cached version.
  1129.     >>> print(e.blog)  # Doesn't hit the database; uses cached version.
  1130.  
  1131. .. _backwards-related-objects:
  1132.  
  1133. Following relationships "backward"
  1134. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1135.  
  1136. If a model has a :class:`~django.db.models.ForeignKey`, instances of the
  1137. foreign-key model will have access to a :class:`~django.db.models.Manager` that
  1138. returns all instances of the first model. By default, this
  1139. :class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the
  1140. source model name, lowercased. This :class:`~django.db.models.Manager` returns
  1141. ``QuerySets``, which can be filtered and manipulated as described in the
  1142. "Retrieving objects" section above.
  1143.  
  1144. Example::
  1145.  
  1146.     >>> b = Blog.objects.get(id=1)
  1147.     >>> b.entry_set.all() # Returns all Entry objects related to Blog.
  1148.  
  1149.     # b.entry_set is a Manager that returns QuerySets.
  1150.     >>> b.entry_set.filter(headline__contains='Lennon')
  1151.     >>> b.entry_set.count()
  1152.  
  1153. You can override the ``FOO_set`` name by setting the
  1154. :attr:`~django.db.models.ForeignKey.related_name` parameter in the
  1155. :class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``
  1156. model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the
  1157. above example code would look like this::
  1158.  
  1159.     >>> b = Blog.objects.get(id=1)
  1160.     >>> b.entries.all() # Returns all Entry objects related to Blog.
  1161.  
  1162.     # b.entries is a Manager that returns QuerySets.
  1163.     >>> b.entries.filter(headline__contains='Lennon')
  1164.     >>> b.entries.count()
  1165.  
  1166. .. _using-custom-reverse-manager:
  1167.  
  1168. Using a custom reverse manager
  1169. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1170.  
  1171. .. versionadded:: 1.7
  1172.  
  1173. By default the :class:`~django.db.models.fields.related.RelatedManager` used
  1174. for reverse relations is a subclass of the :ref:`default manager <manager-names>`
  1175. for that model. If you would like to specify a different manager for a given
  1176. query you can use the following syntax::
  1177.  
  1178.     from django.db import models
  1179.  
  1180.     class Entry(models.Model):
  1181.         #...
  1182.         objects = models.Manager()  # Default Manager
  1183.         entries = EntryManager()    # Custom Manager
  1184.  
  1185.     b = Blog.objects.get(id=1)
  1186.     b.entry_set(manager='entries').all()
  1187.  
  1188. If ``EntryManager`` performed default filtering in its ``get_queryset()``
  1189. method, that filtering would apply to the ``all()`` call.
  1190.  
  1191. Of course, specifying a custom reverse manager also enables you to call its
  1192. custom methods::
  1193.  
  1194.     b.entry_set(manager='entries').is_published()
  1195.  
  1196. Additional methods to handle related objects
  1197. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1198.  
  1199. In addition to the :class:`~django.db.models.query.QuerySet` methods defined in
  1200. "Retrieving objects" above, the :class:`~django.db.models.ForeignKey`
  1201. :class:`~django.db.models.Manager` has additional methods used to handle the
  1202. set of related objects. A synopsis of each is below, and complete details can
  1203. be found in the :doc:`related objects reference </ref/models/relations>`.
  1204.  
  1205. ``add(obj1, obj2, ...)``
  1206.     Adds the specified model objects to the related object set.
  1207.  
  1208. ``create(**kwargs)``
  1209.     Creates a new object, saves it and puts it in the related object set.
  1210.     Returns the newly created object.
  1211.  
  1212. ``remove(obj1, obj2, ...)``
  1213.     Removes the specified model objects from the related object set.
  1214.  
  1215. ``clear()``
  1216.     Removes all objects from the related object set.
  1217.  
  1218. To assign the members of a related set in one fell swoop, just assign to it
  1219. from any iterable object. The iterable can contain object instances, or just
  1220. a list of primary key values. For example::
  1221.  
  1222.     b = Blog.objects.get(id=1)
  1223.     b.entry_set = [e1, e2]
  1224.  
  1225. In this example, ``e1`` and ``e2`` can be full Entry instances, or integer
  1226. primary key values.
  1227.  
  1228. If the ``clear()`` method is available, any pre-existing objects will be
  1229. removed from the ``entry_set`` before all objects in the iterable (in this
  1230. case, a list) are added to the set. If the ``clear()`` method is *not*
  1231. available, all objects in the iterable will be added without removing any
  1232. existing elements.
  1233.  
  1234. Each "reverse" operation described in this section has an immediate effect on
  1235. the database. Every addition, creation and deletion is immediately and
  1236. automatically saved to the database.
  1237.  
  1238. .. _m2m-reverse-relationships:
  1239.  
  1240. Many-to-many relationships
  1241. --------------------------
  1242.  
  1243. Both ends of a many-to-many relationship get automatic API access to the other
  1244. end. The API works just as a "backward" one-to-many relationship, above.
  1245.  
  1246. The only difference is in the attribute naming: The model that defines the
  1247. :class:`~django.db.models.ManyToManyField` uses the attribute name of that
  1248. field itself, whereas the "reverse" model uses the lowercased model name of the
  1249. original model, plus ``'_set'`` (just like reverse one-to-many relationships).
  1250.  
  1251. An example makes this easier to understand::
  1252.  
  1253.     e = Entry.objects.get(id=3)
  1254.     e.authors.all() # Returns all Author objects for this Entry.
  1255.     e.authors.count()
  1256.     e.authors.filter(name__contains='John')
  1257.  
  1258.     a = Author.objects.get(id=5)
  1259.     a.entry_set.all() # Returns all Entry objects for this Author.
  1260.  
  1261. Like :class:`~django.db.models.ForeignKey`,
  1262. :class:`~django.db.models.ManyToManyField` can specify
  1263. :attr:`~django.db.models.ManyToManyField.related_name`. In the above example,
  1264. if the :class:`~django.db.models.ManyToManyField` in ``Entry`` had specified
  1265. ``related_name='entries'``, then each ``Author`` instance would have an
  1266. ``entries`` attribute instead of ``entry_set``.
  1267.  
  1268. One-to-one relationships
  1269. ------------------------
  1270.  
  1271. One-to-one relationships are very similar to many-to-one relationships. If you
  1272. define a :class:`~django.db.models.OneToOneField` on your model, instances of
  1273. that model will have access to the related object via a simple attribute of the
  1274. model.
  1275.  
  1276. For example::
  1277.  
  1278.     class EntryDetail(models.Model):
  1279.         entry = models.OneToOneField(Entry)
  1280.         details = models.TextField()
  1281.  
  1282.     ed = EntryDetail.objects.get(id=2)
  1283.     ed.entry # Returns the related Entry object.
  1284.  
  1285. The difference comes in "reverse" queries. The related model in a one-to-one
  1286. relationship also has access to a :class:`~django.db.models.Manager` object, but
  1287. that :class:`~django.db.models.Manager` represents a single object, rather than
  1288. a collection of objects::
  1289.  
  1290.     e = Entry.objects.get(id=2)
  1291.     e.entrydetail # returns the related EntryDetail object
  1292.  
  1293. If no object has been assigned to this relationship, Django will raise
  1294. a ``DoesNotExist`` exception.
  1295.  
  1296. Instances can be assigned to the reverse relationship in the same way as
  1297. you would assign the forward relationship::
  1298.  
  1299.     e.entrydetail = ed
  1300.  
  1301. How are the backward relationships possible?
  1302. --------------------------------------------
  1303.  
  1304. Other object-relational mappers require you to define relationships on both
  1305. sides. The Django developers believe this is a violation of the DRY (Don't
  1306. Repeat Yourself) principle, so Django only requires you to define the
  1307. relationship on one end.
  1308.  
  1309. But how is this possible, given that a model class doesn't know which other
  1310. model classes are related to it until those other model classes are loaded?
  1311.  
  1312. The answer lies in the :data:`app registry <django.apps.apps>`. When Django
  1313. starts, it imports each application listed in :setting:`INSTALLED_APPS`, and
  1314. then the ``models`` module inside each application. Whenever a new model class
  1315. is created, Django adds backward-relationships to any related models. If the
  1316. related models haven't been imported yet, Django keeps tracks of the
  1317. relationships and adds them when the related models eventually are imported.
  1318.  
  1319. For this reason, it's particularly important that all the models you're using
  1320. be defined in applications listed in :setting:`INSTALLED_APPS`. Otherwise,
  1321. backwards relations may not work properly.
  1322.  
  1323. Queries over related objects
  1324. ----------------------------
  1325.  
  1326. Queries involving related objects follow the same rules as queries involving
  1327. normal value fields. When specifying the value for a query to match, you may
  1328. use either an object instance itself, or the primary key value for the object.
  1329.  
  1330. For example, if you have a Blog object ``b`` with ``id=5``, the following
  1331. three queries would be identical::
  1332.  
  1333.     Entry.objects.filter(blog=b) # Query using object instance
  1334.     Entry.objects.filter(blog=b.id) # Query using id from instance
  1335.     Entry.objects.filter(blog=5) # Query using id directly
  1336.  
  1337. Falling back to raw SQL
  1338. =======================
  1339.  
  1340. If you find yourself needing to write an SQL query that is too complex for
  1341. Django's database-mapper to handle, you can fall back on writing SQL by hand.
  1342. Django has a couple of options for writing raw SQL queries; see
  1343. :doc:`/topics/db/sql`.
  1344.  
  1345. Finally, it's important to note that the Django database layer is merely an
  1346. interface to your database. You can access your database via other tools,
  1347. programming languages or database frameworks; there's nothing Django-specific
  1348. about your data

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.