2008-08-24 06:25:40 +08:00
|
|
|
==============
|
|
|
|
Making queries
|
|
|
|
==============
|
|
|
|
|
|
|
|
.. currentmodule:: django.db.models
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
Once you've created your :doc:`data models </topics/db/models>`, Django
|
2008-08-24 06:25:40 +08:00
|
|
|
automatically gives you a database-abstraction API that lets you create,
|
2009-01-29 18:46:36 +08:00
|
|
|
retrieve, update and delete objects. This document explains how to use this
|
2010-08-20 03:27:44 +08:00
|
|
|
API. Refer to the :doc:`data model reference </ref/models/index>` for full
|
2008-08-24 06:25:40 +08:00
|
|
|
details of all the various model lookup options.
|
|
|
|
|
|
|
|
Throughout this guide (and in the reference), we'll refer to the following
|
2010-10-09 16:12:50 +08:00
|
|
|
models, which comprise a Weblog application:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. _queryset-model-example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
class Blog(models.Model):
|
|
|
|
name = models.CharField(max_length=100)
|
|
|
|
tagline = models.TextField()
|
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
class Author(models.Model):
|
|
|
|
name = models.CharField(max_length=50)
|
|
|
|
email = models.EmailField()
|
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
class Entry(models.Model):
|
|
|
|
blog = models.ForeignKey(Blog)
|
|
|
|
headline = models.CharField(max_length=255)
|
|
|
|
body_text = models.TextField()
|
2012-09-08 23:00:04 +08:00
|
|
|
pub_date = models.DateField()
|
|
|
|
mod_date = models.DateField()
|
2008-08-24 06:25:40 +08:00
|
|
|
authors = models.ManyToManyField(Author)
|
2009-01-29 18:46:36 +08:00
|
|
|
n_comments = models.IntegerField()
|
|
|
|
n_pingbacks = models.IntegerField()
|
|
|
|
rating = models.IntegerField()
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return self.headline
|
|
|
|
|
|
|
|
Creating objects
|
|
|
|
================
|
|
|
|
|
|
|
|
To represent database-table data in Python objects, Django uses an intuitive
|
|
|
|
system: A model class represents a database table, and an instance of that
|
|
|
|
class represents a particular record in the database table.
|
|
|
|
|
|
|
|
To create an object, instantiate it using keyword arguments to the model class,
|
2012-03-03 00:45:06 +08:00
|
|
|
then call :meth:`~django.db.models.Model.save` to save it to the database.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
You import the model class from wherever it lives on the Python path, as you
|
|
|
|
may expect. (We point this out here because previous Django versions required
|
|
|
|
funky model importing.)
|
|
|
|
|
|
|
|
Assuming models live in a file ``mysite/blog/models.py``, here's an example::
|
|
|
|
|
2010-10-19 08:10:22 +08:00
|
|
|
>>> from blog.models import Blog
|
2008-08-24 06:25:40 +08:00
|
|
|
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
|
|
|
|
>>> b.save()
|
|
|
|
|
|
|
|
This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
|
2012-03-03 00:45:06 +08:00
|
|
|
the database until you explicitly call :meth:`~django.db.models.Model.save`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The :meth:`~django.db.models.Model.save` method has no return value.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.Model.save` takes a number of advanced options not
|
2012-03-03 01:16:52 +08:00
|
|
|
described here. See the documentation for
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.Model.save` for complete details.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 01:16:52 +08:00
|
|
|
To create and save an object in a single step, use the
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.query.QuerySet.create()` method.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Saving changes to objects
|
|
|
|
=========================
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
To save changes to an object that's already in the database, use
|
|
|
|
:meth:`~django.db.models.Model.save`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Given a ``Blog`` instance ``b5`` that has already been saved to the database,
|
|
|
|
this example changes its name and updates its record in the database::
|
|
|
|
|
|
|
|
>> b5.name = 'New name'
|
|
|
|
>> b5.save()
|
|
|
|
|
|
|
|
This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
|
2012-03-03 00:45:06 +08:00
|
|
|
the database until you explicitly call :meth:`~django.db.models.Model.save`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Saving ``ForeignKey`` and ``ManyToManyField`` fields
|
|
|
|
----------------------------------------------------
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Updating a :class:`~django.db.models.ForeignKey` field works exactly the same
|
2012-03-03 01:16:52 +08:00
|
|
|
way as saving a normal field -- simply assign an object of the right type to
|
|
|
|
the field in question. This example updates the ``blog`` attribute of an
|
|
|
|
``Entry`` instance ``entry``::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-10-19 08:10:22 +08:00
|
|
|
>>> from blog.models import Entry
|
2010-10-09 16:20:56 +08:00
|
|
|
>>> entry = Entry.objects.get(pk=1)
|
2009-01-29 18:46:36 +08:00
|
|
|
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
|
|
|
|
>>> entry.blog = cheese_blog
|
|
|
|
>>> entry.save()
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Updating a :class:`~django.db.models.ManyToManyField` works a little
|
2012-03-03 01:16:52 +08:00
|
|
|
differently -- use the
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.fields.related.RelatedManager.add` method on the field
|
|
|
|
to add a record to the relation. This example adds the ``Author`` instance
|
|
|
|
``joe`` to the ``entry`` object::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-10-19 08:10:22 +08:00
|
|
|
>>> from blog.models import Author
|
2010-10-09 16:20:56 +08:00
|
|
|
>>> joe = Author.objects.create(name="Joe")
|
|
|
|
>>> entry.authors.add(joe)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
To add multiple records to a :class:`~django.db.models.ManyToManyField` in one
|
|
|
|
go, include multiple arguments in the call to
|
|
|
|
:meth:`~django.db.models.fields.related.RelatedManager.add`, like this::
|
2011-08-26 12:34:40 +08:00
|
|
|
|
|
|
|
>>> john = Author.objects.create(name="John")
|
|
|
|
>>> paul = Author.objects.create(name="Paul")
|
|
|
|
>>> george = Author.objects.create(name="George")
|
|
|
|
>>> ringo = Author.objects.create(name="Ringo")
|
|
|
|
>>> entry.authors.add(john, paul, george, ringo)
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Django will complain if you try to assign or add an object of the wrong type.
|
|
|
|
|
|
|
|
Retrieving objects
|
|
|
|
==================
|
|
|
|
|
2012-03-03 01:16:52 +08:00
|
|
|
To retrieve objects from your database, construct a
|
2012-03-03 00:45:06 +08:00
|
|
|
:class:`~django.db.models.query.QuerySet` via a
|
|
|
|
:class:`~django.db.models.Manager` on your model class.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
A :class:`~django.db.models.query.QuerySet` represents a collection of objects
|
|
|
|
from your database. It can have zero, one or many *filters* -- criteria that
|
|
|
|
narrow down the collection based on given parameters. In SQL terms, a
|
|
|
|
:class:`~django.db.models.query.QuerySet` equates to a ``SELECT`` statement,
|
|
|
|
and a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
You get a :class:`~django.db.models.query.QuerySet` by using your model's
|
|
|
|
:class:`~django.db.models.Manager`. Each model has at least one
|
|
|
|
:class:`~django.db.models.Manager`, and it's called ``objects`` by
|
|
|
|
default. Access it directly via the model class, like so::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> Blog.objects
|
|
|
|
<django.db.models.manager.Manager object at ...>
|
|
|
|
>>> b = Blog(name='Foo', tagline='Bar')
|
|
|
|
>>> b.objects
|
|
|
|
Traceback:
|
|
|
|
...
|
|
|
|
AttributeError: "Manager isn't accessible via Blog instances."
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
``Managers`` are accessible only via model classes, rather than from model
|
|
|
|
instances, to enforce a separation between "table-level" operations and
|
|
|
|
"record-level" operations.
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The :class:`~django.db.models.Manager` is the main source of ``QuerySets`` for
|
|
|
|
a model. It acts as a "root" :class:`~django.db.models.query.QuerySet` that
|
2012-03-03 01:16:52 +08:00
|
|
|
describes all objects in the model's database table. For example,
|
2012-03-03 00:45:06 +08:00
|
|
|
``Blog.objects`` is the initial :class:`~django.db.models.query.QuerySet` that
|
|
|
|
contains all ``Blog`` objects in the database.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Retrieving all objects
|
|
|
|
----------------------
|
|
|
|
|
2012-03-03 01:16:52 +08:00
|
|
|
The simplest way to retrieve objects from a table is to get all of them. To do
|
2012-03-03 00:45:06 +08:00
|
|
|
this, use the :meth:`~django.db.models.query.QuerySet.all` method on a
|
|
|
|
:class:`~django.db.models.Manager`::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> all_entries = Entry.objects.all()
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The :meth:`~django.db.models.query.QuerySet.all` method returns a
|
|
|
|
:class:`~django.db.models.query.QuerySet` of all the objects in the database.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
(If ``Entry.objects`` is a :class:`~django.db.models.query.QuerySet`, why can't
|
|
|
|
we just do ``Entry.objects``? That's because ``Entry.objects``, the root
|
|
|
|
:class:`~django.db.models.query.QuerySet`, is a special case that cannot be
|
|
|
|
evaluated. The :meth:`~django.db.models.query.QuerySet.all` method returns a
|
|
|
|
:class:`~django.db.models.query.QuerySet` that *can* be evaluated.)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-12-05 06:32:01 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Retrieving specific objects with filters
|
|
|
|
----------------------------------------
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The root :class:`~django.db.models.query.QuerySet` provided by the
|
|
|
|
:class:`~django.db.models.Manager` describes all objects in the database
|
|
|
|
table. Usually, though, you'll need to select only a subset of the complete set
|
|
|
|
of objects.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
To create such a subset, you refine the initial
|
|
|
|
:class:`~django.db.models.query.QuerySet`, adding filter conditions. The two
|
|
|
|
most common ways to refine a :class:`~django.db.models.query.QuerySet` are:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
``filter(**kwargs)``
|
2012-03-03 00:45:06 +08:00
|
|
|
Returns a new :class:`~django.db.models.query.QuerySet` containing objects
|
|
|
|
that match the given lookup parameters.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
``exclude(**kwargs)``
|
2012-03-03 00:45:06 +08:00
|
|
|
Returns a new :class:`~django.db.models.query.QuerySet` containing objects
|
|
|
|
that do *not* match the given lookup parameters.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
The lookup parameters (``**kwargs`` in the above function definitions) should
|
|
|
|
be in the format described in `Field lookups`_ below.
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
For example, to get a :class:`~django.db.models.query.QuerySet` of blog entries
|
|
|
|
from the year 2006, use :meth:`~django.db.models.query.QuerySet.filter` like
|
|
|
|
so::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Entry.objects.filter(pub_date__year=2006)
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
We don't have to add an :meth:`~django.db.models.query.QuerySet.all` --
|
|
|
|
``Entry.objects.all().filter(...)``. That would still work, but you only need
|
|
|
|
:meth:`~django.db.models.query.QuerySet.all` when you want all objects from the
|
|
|
|
root :class:`~django.db.models.query.QuerySet`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. _chaining-filters:
|
|
|
|
|
|
|
|
Chaining filters
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The result of refining a :class:`~django.db.models.query.QuerySet` is itself a
|
|
|
|
:class:`~django.db.models.query.QuerySet`, so it's possible to chain
|
|
|
|
refinements together. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> Entry.objects.filter(
|
|
|
|
... headline__startswith='What'
|
|
|
|
... ).exclude(
|
2012-09-08 23:00:04 +08:00
|
|
|
... pub_date__gte=datetime.date.today()
|
2008-08-24 06:25:40 +08:00
|
|
|
... ).filter(
|
2012-09-03 23:31:37 +08:00
|
|
|
... pub_date__gte=datetime(2005, 1, 30)
|
2008-08-24 06:25:40 +08:00
|
|
|
... )
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
This takes the initial :class:`~django.db.models.query.QuerySet` of all entries
|
|
|
|
in the database, adds a filter, then an exclusion, then another filter. The
|
|
|
|
final result is a :class:`~django.db.models.query.QuerySet` containing all
|
|
|
|
entries with a headline that starts with "What", that were published between
|
2012-09-03 23:31:37 +08:00
|
|
|
January 30, 2005, and the current day.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. _filtered-querysets-are-unique:
|
|
|
|
|
|
|
|
Filtered QuerySets are unique
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Each time you refine a :class:`~django.db.models.query.QuerySet`, you get a
|
|
|
|
brand-new :class:`~django.db.models.query.QuerySet` that is in no way bound to
|
|
|
|
the previous :class:`~django.db.models.query.QuerySet`. Each refinement creates
|
|
|
|
a separate and distinct :class:`~django.db.models.query.QuerySet` that can be
|
|
|
|
stored, used and reused.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
>> q1 = Entry.objects.filter(headline__startswith="What")
|
2012-09-08 23:00:04 +08:00
|
|
|
>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
|
|
|
|
>> q3 = q1.filter(pub_date__gte=datetime.date.today())
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
These three ``QuerySets`` are separate. The first is a base
|
|
|
|
:class:`~django.db.models.query.QuerySet` containing all entries that contain a
|
|
|
|
headline starting with "What". The second is a subset of the first, with an
|
|
|
|
additional criteria that excludes records whose ``pub_date`` is greater than
|
|
|
|
now. The third is a subset of the first, with an additional criteria that
|
|
|
|
selects only the records whose ``pub_date`` is greater than now. The initial
|
|
|
|
:class:`~django.db.models.query.QuerySet` (``q1``) is unaffected by the
|
2008-08-24 06:25:40 +08:00
|
|
|
refinement process.
|
|
|
|
|
|
|
|
.. _querysets-are-lazy:
|
|
|
|
|
|
|
|
QuerySets are lazy
|
|
|
|
~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
``QuerySets`` are lazy -- the act of creating a
|
|
|
|
:class:`~django.db.models.query.QuerySet` doesn't involve any database
|
|
|
|
activity. You can stack filters together all day long, and Django won't
|
|
|
|
actually run the query until the :class:`~django.db.models.query.QuerySet` is
|
|
|
|
*evaluated*. Take a look at this example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> q = Entry.objects.filter(headline__startswith="What")
|
2012-09-08 23:00:04 +08:00
|
|
|
>>> q = q.filter(pub_date__lte=datetime.date.today())
|
2008-08-24 06:25:40 +08:00
|
|
|
>>> q = q.exclude(body_text__icontains="food")
|
2012-04-29 00:02:01 +08:00
|
|
|
>>> print(q)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Though this looks like three database hits, in fact it hits the database only
|
2012-04-29 00:02:01 +08:00
|
|
|
once, at the last line (``print(q)``). In general, the results of a
|
2012-03-03 00:45:06 +08:00
|
|
|
:class:`~django.db.models.query.QuerySet` aren't fetched from the database
|
|
|
|
until you "ask" for them. When you do, the
|
|
|
|
:class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the
|
|
|
|
database. For more details on exactly when evaluation takes place, see
|
|
|
|
:ref:`when-querysets-are-evaluated`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-12-05 06:32:01 +08:00
|
|
|
|
|
|
|
.. _retrieving-single-object-with-get:
|
|
|
|
|
|
|
|
Retrieving a single object with get
|
|
|
|
-----------------------------------
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` will always give you a
|
|
|
|
:class:`~django.db.models.query.QuerySet`, even if only a single object matches
|
|
|
|
the query - in this case, it will be a
|
|
|
|
:class:`~django.db.models.query.QuerySet` containing a single element.
|
2010-12-05 06:32:01 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
If you know there is only one object that matches your query, you can use the
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get` method on a `Manager` which
|
|
|
|
returns the object directly::
|
2010-12-05 06:32:01 +08:00
|
|
|
|
|
|
|
>>> one_entry = Entry.objects.get(pk=1)
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
You can use any query expression with
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get`, just like with
|
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` - again, see `Field lookups`_
|
|
|
|
below.
|
2010-12-05 06:32:01 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Note that there is a difference between using
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get`, and using
|
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` with a slice of ``[0]``. If
|
|
|
|
there are no results that match the query,
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get` will raise a ``DoesNotExist``
|
|
|
|
exception. This exception is an attribute of the model class that the query is
|
|
|
|
being performed on - so in the code above, if there is no ``Entry`` object with
|
|
|
|
a primary key of 1, Django will raise ``Entry.DoesNotExist``.
|
2010-12-05 06:32:01 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Similarly, Django will complain if more than one item matches the
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get` query. In this case, it will raise
|
|
|
|
``MultipleObjectsReturned``, which again is an attribute of the model class
|
|
|
|
itself.
|
2010-12-05 06:32:01 +08:00
|
|
|
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Other QuerySet methods
|
2010-12-05 06:32:01 +08:00
|
|
|
----------------------
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Most of the time you'll use :meth:`~django.db.models.query.QuerySet.all`,
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get`,
|
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` and
|
|
|
|
:meth:`~django.db.models.query.QuerySet.exclude` when you 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 of all the
|
|
|
|
various :class:`~django.db.models.query.QuerySet` methods.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. _limiting-querysets:
|
|
|
|
|
|
|
|
Limiting QuerySets
|
|
|
|
------------------
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Use a subset of Python's array-slicing syntax to limit your
|
|
|
|
:class:`~django.db.models.query.QuerySet` to a certain number of results. This
|
|
|
|
is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
For example, this returns the first 5 objects (``LIMIT 5``)::
|
|
|
|
|
|
|
|
>>> Entry.objects.all()[:5]
|
|
|
|
|
|
|
|
This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
|
|
|
|
|
|
|
|
>>> Entry.objects.all()[5:10]
|
2009-06-18 21:32:48 +08:00
|
|
|
|
2009-05-23 20:58:31 +08:00
|
|
|
Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Generally, slicing a :class:`~django.db.models.query.QuerySet` returns a new
|
|
|
|
:class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An
|
|
|
|
exception is if you use the "step" parameter of Python slice syntax. For
|
|
|
|
example, this would actually execute the query in order to return a list of
|
|
|
|
every *second* object of the first 10::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> Entry.objects.all()[:10:2]
|
|
|
|
|
|
|
|
To retrieve a *single* object rather than a list
|
|
|
|
(e.g. ``SELECT foo FROM bar LIMIT 1``), use a simple index instead of a
|
|
|
|
slice. For example, this returns the first ``Entry`` in the database, after
|
|
|
|
ordering entries alphabetically by headline::
|
|
|
|
|
|
|
|
>>> Entry.objects.order_by('headline')[0]
|
|
|
|
|
|
|
|
This is roughly equivalent to::
|
|
|
|
|
|
|
|
>>> Entry.objects.order_by('headline')[0:1].get()
|
|
|
|
|
|
|
|
Note, however, that the first of these will raise ``IndexError`` while the
|
|
|
|
second will raise ``DoesNotExist`` if no objects match the given criteria. See
|
2011-09-30 18:28:39 +08:00
|
|
|
:meth:`~django.db.models.query.QuerySet.get` for more details.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. _field-lookups-intro:
|
|
|
|
|
|
|
|
Field lookups
|
|
|
|
-------------
|
|
|
|
|
|
|
|
Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
|
2012-03-03 00:45:06 +08:00
|
|
|
specified as keyword arguments to the :class:`~django.db.models.query.QuerySet`
|
|
|
|
methods :meth:`~django.db.models.query.QuerySet.filter`,
|
|
|
|
:meth:`~django.db.models.query.QuerySet.exclude` and
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Basic lookups keyword arguments take the form ``field__lookuptype=value``.
|
|
|
|
(That's a double-underscore). For example::
|
|
|
|
|
|
|
|
>>> Entry.objects.filter(pub_date__lte='2006-01-01')
|
|
|
|
|
|
|
|
translates (roughly) into the following SQL::
|
|
|
|
|
|
|
|
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
|
|
|
|
|
|
|
|
.. admonition:: How this is possible
|
|
|
|
|
|
|
|
Python has the ability to define functions that accept arbitrary name-value
|
|
|
|
arguments whose names and values are evaluated at runtime. For more
|
|
|
|
information, see `Keyword Arguments`_ in the official Python tutorial.
|
|
|
|
|
2009-12-26 14:37:26 +08:00
|
|
|
.. _`Keyword Arguments`: http://docs.python.org/tutorial/controlflow.html#keyword-arguments
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-06-28 18:16:18 +08:00
|
|
|
.. versionchanged:: 1.4
|
|
|
|
The field specified in a lookup has to be the name of a model field.
|
|
|
|
There's one exception though, in case of a
|
2012-03-03 00:45:06 +08:00
|
|
|
:class:`~django.db.models.ForeignKey` you can specify the field
|
2011-06-28 18:16:18 +08:00
|
|
|
name suffixed with ``_id``. In this case, the value parameter is expected
|
|
|
|
to contain the raw value of the foreign model's primary key. For example::
|
|
|
|
|
|
|
|
>>> Entry.objects.filter(blog_id__exact=4)
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
If you pass an invalid keyword argument, a lookup function will raise
|
|
|
|
``TypeError``.
|
|
|
|
|
|
|
|
The database API supports about two dozen lookup types; a complete reference
|
2012-03-03 00:45:06 +08:00
|
|
|
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 you'll
|
|
|
|
probably use:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
:lookup:`exact`
|
|
|
|
An "exact" match. For example::
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
>>> Entry.objects.get(headline__exact="Man bites dog")
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
Would generate SQL along these lines:
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
.. code-block:: sql
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
SELECT ... WHERE headline = 'Man bites dog';
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
If you don't provide a lookup type -- that is, if your keyword argument
|
|
|
|
doesn't contain a double underscore -- the lookup type is assumed to be
|
|
|
|
``exact``.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
For example, the following two statements are equivalent::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
>>> Blog.objects.get(id__exact=14) # Explicit form
|
|
|
|
>>> Blog.objects.get(id=14) # __exact is implied
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
This is for convenience, because ``exact`` lookups are the common case.
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
:lookup:`iexact`
|
|
|
|
A case-insensitive match. So, the query::
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
>>> Blog.objects.get(name__iexact="beatles blog")
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
Would match a ``Blog`` titled "Beatles Blog", "beatles blog", or even
|
|
|
|
"BeAtlES blOG".
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
:lookup:`contains`
|
|
|
|
Case-sensitive containment test. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
Entry.objects.get(headline__contains='Lennon')
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
Roughly translates to this SQL:
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
.. code-block:: sql
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
SELECT ... WHERE headline LIKE '%Lennon%';
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
Note this will match the headline ``'Today Lennon honored'`` but not
|
|
|
|
``'today lennon honored'``.
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
There's also a case-insensitive version, :lookup:`icontains`.
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
:lookup:`startswith`, :lookup:`endswith`
|
|
|
|
Starts-with and ends-with search, respectively. There are also
|
|
|
|
case-insensitive versions called :lookup:`istartswith` and
|
|
|
|
:lookup:`iendswith`.
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Again, this only scratches the surface. A complete reference can be found in the
|
|
|
|
:ref:`field lookup reference <field-lookups>`.
|
|
|
|
|
2012-03-15 06:16:46 +08:00
|
|
|
.. _lookups-that-span-relationships:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Lookups that span relationships
|
|
|
|
-------------------------------
|
|
|
|
|
|
|
|
Django offers a powerful and intuitive way to "follow" relationships in
|
|
|
|
lookups, taking care of the SQL ``JOIN``\s for you automatically, behind the
|
|
|
|
scenes. To span a relationship, just use the field name of related fields
|
|
|
|
across models, separated by double underscores, until you get to the field you
|
|
|
|
want.
|
|
|
|
|
|
|
|
This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
|
|
|
|
is ``'Beatles Blog'``::
|
|
|
|
|
|
|
|
>>> Entry.objects.filter(blog__name__exact='Beatles Blog')
|
|
|
|
|
|
|
|
This spanning can be as deep as you'd like.
|
|
|
|
|
|
|
|
It works backwards, too. To refer to a "reverse" relationship, just use the
|
|
|
|
lowercase name of the model.
|
|
|
|
|
|
|
|
This example retrieves all ``Blog`` objects which have at least one ``Entry``
|
|
|
|
whose ``headline`` contains ``'Lennon'``::
|
|
|
|
|
|
|
|
>>> Blog.objects.filter(entry__headline__contains='Lennon')
|
|
|
|
|
|
|
|
If you are filtering across multiple relationships and one of the intermediate
|
|
|
|
models doesn't have a value that meets the filter condition, Django will treat
|
|
|
|
it as if there is an empty (all values are ``NULL``), but valid, object there.
|
|
|
|
All this means is that no error will be raised. For example, in this filter::
|
|
|
|
|
2010-04-05 23:57:00 +08:00
|
|
|
Blog.objects.filter(entry__authors__name='Lennon')
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
(if there was a related ``Author`` model), if there was no ``author``
|
|
|
|
associated with an entry, it would be treated as if there was also no ``name``
|
|
|
|
attached, rather than raising an error because of the missing ``author``.
|
|
|
|
Usually this is exactly what you want to have happen. The only case where it
|
2012-03-03 00:45:06 +08:00
|
|
|
might be confusing is if you are using :lookup:`isnull`. Thus::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-04-05 23:57:00 +08:00
|
|
|
Blog.objects.filter(entry__authors__name__isnull=True)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
will return ``Blog`` objects that have an empty ``name`` on the ``author`` and
|
|
|
|
also those which have an empty ``author`` on the ``entry``. If you don't want
|
|
|
|
those latter objects, you could write::
|
|
|
|
|
2010-04-05 23:57:00 +08:00
|
|
|
Blog.objects.filter(entry__authors__isnull=False,
|
|
|
|
entry__authors__name__isnull=True)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Spanning multi-valued relationships
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
When you are filtering an object based on a
|
|
|
|
:class:`~django.db.models.ManyToManyField` or a reverse
|
|
|
|
:class:`~django.db.models.ForeignKey`, there are two different sorts of filter
|
|
|
|
you may be interested in. Consider the ``Blog``/``Entry`` relationship
|
|
|
|
(``Blog`` to ``Entry`` is a one-to-many relation). We might be interested in
|
|
|
|
finding blogs that have an entry which has both *"Lennon"* in the headline and
|
|
|
|
was published in 2008. Or we might want to find blogs that have an entry with
|
|
|
|
*"Lennon"* in the headline as well as an entry that was published
|
|
|
|
in 2008. Since there are multiple entries associated with a single ``Blog``,
|
|
|
|
both of these queries are possible and make sense in some situations.
|
|
|
|
|
|
|
|
The same type of situation arises with a
|
|
|
|
:class:`~django.db.models.ManyToManyField`. For example, if an ``Entry`` has a
|
|
|
|
:class:`~django.db.models.ManyToManyField` called ``tags``, we might want to
|
|
|
|
find entries linked to tags called *"music"* and *"bands"* or we might want an
|
2008-08-24 06:25:40 +08:00
|
|
|
entry that contains a tag with a name of *"music"* and a status of *"public"*.
|
|
|
|
|
|
|
|
To handle both of these situations, Django has a consistent way of processing
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` and
|
2012-03-03 01:16:52 +08:00
|
|
|
:meth:`~django.db.models.query.QuerySet.exclude` calls. Everything inside a
|
2012-03-03 00:45:06 +08:00
|
|
|
single :meth:`~django.db.models.query.QuerySet.filter` call is applied
|
|
|
|
simultaneously to filter out items matching all those requirements. Successive
|
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` calls further restrict the set
|
|
|
|
of objects, but for multi-valued relations, they apply to any object linked to
|
2008-08-24 06:25:40 +08:00
|
|
|
the primary model, not necessarily those objects that were selected by an
|
2012-03-03 00:45:06 +08:00
|
|
|
earlier :meth:`~django.db.models.query.QuerySet.filter` call.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
That may sound a bit confusing, so hopefully an example will clarify. To
|
2009-03-03 09:40:47 +08:00
|
|
|
select all blogs that contain entries with both *"Lennon"* in the headline
|
|
|
|
and that were published in 2008 (the same entry satisfying both conditions),
|
|
|
|
we would write::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Blog.objects.filter(entry__headline__contains='Lennon',
|
|
|
|
entry__pub_date__year=2008)
|
|
|
|
|
|
|
|
To select all blogs that contain an entry with *"Lennon"* in the headline
|
|
|
|
**as well as** an entry that was published in 2008, we would write::
|
|
|
|
|
|
|
|
Blog.objects.filter(entry__headline__contains='Lennon').filter(
|
|
|
|
entry__pub_date__year=2008)
|
|
|
|
|
|
|
|
In this second example, the first filter restricted the queryset to all those
|
|
|
|
blogs linked to that particular type of entry. The second filter restricted
|
|
|
|
the set of blogs *further* to those that are also linked to the second type of
|
|
|
|
entry. The entries select by the second filter may or may not be the same as
|
|
|
|
the entries in the first filter. We are filtering the ``Blog`` items with each
|
|
|
|
filter statement, not the ``Entry`` items.
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
All of this behavior also applies to
|
|
|
|
:meth:`~django.db.models.query.QuerySet.exclude`: all the conditions in a
|
|
|
|
single :meth:`~django.db.models.query.QuerySet.exclude` statement apply to a
|
|
|
|
single instance (if those conditions are talking about the same multi-valued
|
|
|
|
relation). Conditions in subsequent
|
|
|
|
:meth:`~django.db.models.query.QuerySet.filter` or
|
|
|
|
:meth:`~django.db.models.query.QuerySet.exclude` calls that refer to the same
|
|
|
|
relation may end up filtering on different linked objects.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
.. _query-expressions:
|
|
|
|
|
|
|
|
Filters can reference fields on the model
|
|
|
|
-----------------------------------------
|
|
|
|
|
|
|
|
In the examples given so far, we have constructed filters that compare
|
|
|
|
the value of a model field with a constant. But what if you want to compare
|
|
|
|
the value of a model field with another field on the same model?
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Django provides the :ref:`F() expressions <query-expressions>` to allow such
|
|
|
|
comparisons. Instances of ``F()`` act as a reference to a model field within a
|
|
|
|
query. These references can then be used in query filters to compare the values
|
|
|
|
of two different fields on the same model instance.
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
For example, to find a list of all blog entries that have had more comments
|
2011-04-24 05:48:23 +08:00
|
|
|
than pingbacks, we construct an ``F()`` object to reference the pingback count,
|
2009-01-29 18:46:36 +08:00
|
|
|
and use that ``F()`` object in the query::
|
|
|
|
|
2009-02-04 07:13:02 +08:00
|
|
|
>>> from django.db.models import F
|
2010-05-14 09:51:14 +08:00
|
|
|
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
Django supports the use of addition, subtraction, multiplication,
|
|
|
|
division and modulo arithmetic with ``F()`` objects, both with constants
|
2010-05-14 09:51:14 +08:00
|
|
|
and with other ``F()`` objects. To find all the blog entries with more than
|
|
|
|
*twice* as many comments as pingbacks, we modify the query::
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2010-05-14 09:51:14 +08:00
|
|
|
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2010-05-14 09:51:14 +08:00
|
|
|
To find all the entries where the rating of the entry is less than the
|
|
|
|
sum of the pingback count and comment count, we would issue the
|
|
|
|
query::
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
>>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
|
|
|
|
|
|
|
|
You can also use the double underscore notation to span relationships in
|
|
|
|
an ``F()`` object. An ``F()`` object with a double underscore will introduce
|
|
|
|
any joins needed to access the related object. For example, to retrieve all
|
|
|
|
the entries where the author's name is the same as the blog name, we could
|
2010-12-22 11:34:04 +08:00
|
|
|
issue the query::
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2010-04-05 23:57:00 +08:00
|
|
|
>>> Entry.objects.filter(authors__name=F('blog__name'))
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2010-12-22 11:34:04 +08:00
|
|
|
.. versionadded:: 1.3
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
For date and date/time fields, you can add or subtract a
|
2012-03-03 01:16:52 +08:00
|
|
|
:class:`~datetime.timedelta` object. The following would return all entries
|
2012-03-03 00:45:06 +08:00
|
|
|
that were modified more than 3 days after they were published::
|
2011-04-22 22:08:31 +08:00
|
|
|
|
2010-12-22 11:34:04 +08:00
|
|
|
>>> from datetime import timedelta
|
|
|
|
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
The pk lookup shortcut
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
For convenience, Django provides a ``pk`` lookup shortcut, which stands for
|
|
|
|
"primary key".
|
|
|
|
|
|
|
|
In the example ``Blog`` model, the primary key is the ``id`` field, so these
|
|
|
|
three statements are equivalent::
|
|
|
|
|
|
|
|
>>> Blog.objects.get(id__exact=14) # Explicit form
|
|
|
|
>>> Blog.objects.get(id=14) # __exact is implied
|
|
|
|
>>> Blog.objects.get(pk=14) # pk implies id__exact
|
|
|
|
|
|
|
|
The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
|
|
|
|
can be combined with ``pk`` to perform a query on the primary key of a model::
|
|
|
|
|
|
|
|
# Get blogs entries with id 1, 4 and 7
|
|
|
|
>>> Blog.objects.filter(pk__in=[1,4,7])
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
# Get all blog entries with id > 14
|
|
|
|
>>> Blog.objects.filter(pk__gt=14)
|
|
|
|
|
|
|
|
``pk`` lookups also work across joins. For example, these three statements are
|
|
|
|
equivalent::
|
|
|
|
|
|
|
|
>>> Entry.objects.filter(blog__id__exact=3) # Explicit form
|
|
|
|
>>> Entry.objects.filter(blog__id=3) # __exact is implied
|
|
|
|
>>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
|
|
|
|
|
|
|
|
Escaping percent signs and underscores in LIKE statements
|
|
|
|
---------------------------------------------------------
|
|
|
|
|
|
|
|
The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
|
|
|
|
``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``
|
|
|
|
and ``iendswith``) will automatically escape the two special characters used in
|
|
|
|
``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
|
|
|
|
statement, the percent sign signifies a multiple-character wildcard and the
|
|
|
|
underscore signifies a single-character wildcard.)
|
|
|
|
|
|
|
|
This means things should work intuitively, so the abstraction doesn't leak.
|
|
|
|
For example, to retrieve all the entries that contain a percent sign, just use
|
|
|
|
the percent sign as any other character::
|
|
|
|
|
|
|
|
>>> Entry.objects.filter(headline__contains='%')
|
|
|
|
|
|
|
|
Django takes care of the quoting for you; the resulting SQL will look something
|
|
|
|
like this:
|
|
|
|
|
|
|
|
.. code-block:: sql
|
|
|
|
|
|
|
|
SELECT ... WHERE headline LIKE '%\%%';
|
|
|
|
|
|
|
|
Same goes for underscores. Both percentage signs and underscores are handled
|
|
|
|
for you transparently.
|
|
|
|
|
|
|
|
.. _caching-and-querysets:
|
|
|
|
|
|
|
|
Caching and QuerySets
|
|
|
|
---------------------
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Each :class:`~django.db.models.query.QuerySet` contains a cache, to minimize
|
|
|
|
database access. It's important to understand how it works, in order to write
|
|
|
|
the most efficient code.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
In a newly created :class:`~django.db.models.query.QuerySet`, the cache is
|
|
|
|
empty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated
|
|
|
|
-- and, hence, a database query happens -- Django saves the query results in
|
|
|
|
the :class:`~django.db.models.query.QuerySet`\'s cache and returns the results
|
2008-08-24 06:25:40 +08:00
|
|
|
that have been explicitly requested (e.g., the next element, if the
|
2012-03-03 00:45:06 +08:00
|
|
|
:class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent
|
|
|
|
evaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached
|
|
|
|
results.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Keep this caching behavior in mind, because it may bite you if you don't use
|
2012-03-03 00:45:06 +08:00
|
|
|
your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
|
|
|
|
following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
|
|
|
|
them, and throw them away::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-04-29 00:02:01 +08:00
|
|
|
>>> print([e.headline for e in Entry.objects.all()])
|
|
|
|
>>> print([e.pub_date for e in Entry.objects.all()])
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
That means the same database query will be executed twice, effectively doubling
|
|
|
|
your database load. Also, there's a possibility the two lists may not include
|
|
|
|
the same database records, because an ``Entry`` may have been added or deleted
|
|
|
|
in the split second between the two requests.
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
To avoid this problem, simply save the
|
|
|
|
:class:`~django.db.models.query.QuerySet` and reuse it::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-01-11 05:28:37 +08:00
|
|
|
>>> queryset = Entry.objects.all()
|
2012-04-29 00:02:01 +08:00
|
|
|
>>> print([p.headline for p in queryset]) # Evaluate the query set.
|
|
|
|
>>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2009-09-24 07:40:12 +08:00
|
|
|
.. _complex-lookups-with-q:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Complex lookups with Q objects
|
|
|
|
==============================
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
|
|
|
|
etc. -- are "AND"ed together. If you need to execute more complex queries (for
|
|
|
|
example, queries with ``OR`` statements), you can use ``Q`` objects.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
.. comment: Link to Q does not work, since this documentation does not exist yet.
|
|
|
|
|
|
|
|
A :class:`~django.db.models.Q` object (``django.db.models.Q``) is an object
|
|
|
|
used to encapsulate a collection of keyword arguments. These keyword arguments
|
|
|
|
are specified as in "Field lookups" above.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
For example, this ``Q`` object encapsulates a single ``LIKE`` query::
|
|
|
|
|
2011-03-04 05:04:32 +08:00
|
|
|
from django.db.models import Q
|
2008-08-24 06:25:40 +08:00
|
|
|
Q(question__startswith='What')
|
|
|
|
|
|
|
|
``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
|
|
|
|
operator is used on two ``Q`` objects, it yields a new ``Q`` object.
|
|
|
|
|
|
|
|
For example, this statement yields a single ``Q`` object that represents the
|
|
|
|
"OR" of two ``"question__startswith"`` queries::
|
|
|
|
|
|
|
|
Q(question__startswith='Who') | Q(question__startswith='What')
|
|
|
|
|
|
|
|
This is equivalent to the following SQL ``WHERE`` clause::
|
|
|
|
|
|
|
|
WHERE question LIKE 'Who%' OR question LIKE 'What%'
|
|
|
|
|
|
|
|
You can compose statements of arbitrary complexity by combining ``Q`` objects
|
2008-10-24 17:25:32 +08:00
|
|
|
with the ``&`` and ``|`` operators and use parenthetical grouping. Also, ``Q``
|
|
|
|
objects can be negated using the ``~`` operator, allowing for combined lookups
|
|
|
|
that combine both a normal query and a negated (``NOT``) query::
|
|
|
|
|
|
|
|
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Each lookup function that takes keyword-arguments
|
|
|
|
(e.g. :meth:`~django.db.models.query.QuerySet.filter`,
|
|
|
|
:meth:`~django.db.models.query.QuerySet.exclude`,
|
|
|
|
:meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more
|
|
|
|
``Q`` objects as positional (not-named) arguments. If you provide multiple
|
|
|
|
``Q`` object arguments to a lookup function, the arguments will be "AND"ed
|
|
|
|
together. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Poll.objects.get(
|
|
|
|
Q(question__startswith='Who'),
|
|
|
|
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
|
|
|
|
)
|
|
|
|
|
|
|
|
... roughly translates into the SQL::
|
|
|
|
|
|
|
|
SELECT * from polls WHERE question LIKE 'Who%'
|
|
|
|
AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
|
|
|
|
|
|
|
|
Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
|
|
|
|
arguments provided to a lookup function (be they keyword arguments or ``Q``
|
|
|
|
objects) are "AND"ed together. However, if a ``Q`` object is provided, it must
|
|
|
|
precede the definition of any keyword arguments. For example::
|
|
|
|
|
|
|
|
Poll.objects.get(
|
|
|
|
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
|
|
|
|
question__startswith='Who')
|
|
|
|
|
|
|
|
... would be a valid query, equivalent to the previous example; but::
|
|
|
|
|
|
|
|
# INVALID QUERY
|
|
|
|
Poll.objects.get(
|
|
|
|
question__startswith='Who',
|
|
|
|
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
|
|
|
|
|
|
|
|
... would not be valid.
|
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
2008-09-01 17:45:30 +08:00
|
|
|
The `OR lookups examples`_ in the Django unit tests show some possible uses
|
|
|
|
of ``Q``.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-05-03 23:42:56 +08:00
|
|
|
.. _OR lookups examples: https://github.com/django/django/blob/master/tests/modeltests/or_lookups/tests.py
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Comparing objects
|
|
|
|
=================
|
|
|
|
|
|
|
|
To compare two model instances, just use the standard Python comparison operator,
|
|
|
|
the double equals sign: ``==``. Behind the scenes, that compares the primary
|
|
|
|
key values of two models.
|
|
|
|
|
|
|
|
Using the ``Entry`` example above, the following two statements are equivalent::
|
|
|
|
|
|
|
|
>>> some_entry == other_entry
|
|
|
|
>>> some_entry.id == other_entry.id
|
|
|
|
|
|
|
|
If a model's primary key isn't called ``id``, no problem. Comparisons will
|
|
|
|
always use the primary key, whatever it's called. For example, if a model's
|
|
|
|
primary key field is called ``name``, these two statements are equivalent::
|
|
|
|
|
|
|
|
>>> some_obj == other_obj
|
|
|
|
>>> some_obj.name == other_obj.name
|
|
|
|
|
2009-03-11 15:06:50 +08:00
|
|
|
.. _topics-db-queries-delete:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Deleting objects
|
|
|
|
================
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The delete method, conveniently, is named
|
|
|
|
:meth:`~django.db.models.Model.delete`. This method immediately deletes the
|
|
|
|
object and has no return value. Example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
e.delete()
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
You can also delete objects in bulk. Every
|
|
|
|
:class:`~django.db.models.query.QuerySet` has a
|
|
|
|
:meth:`~django.db.models.query.QuerySet.delete` method, which deletes all
|
|
|
|
members of that :class:`~django.db.models.query.QuerySet`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
|
|
|
|
2005::
|
|
|
|
|
|
|
|
Entry.objects.filter(pub_date__year=2005).delete()
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Keep in mind that this will, whenever possible, be executed purely in SQL, and
|
|
|
|
so the ``delete()`` methods of individual object instances will not necessarily
|
|
|
|
be called during the process. If you've provided a custom ``delete()`` method
|
|
|
|
on a model class and want to ensure that it is called, you will need to
|
|
|
|
"manually" delete instances of that model (e.g., by iterating over a
|
|
|
|
:class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each
|
|
|
|
object individually) rather than using the bulk
|
|
|
|
:meth:`~django.db.models.query.QuerySet.delete` method of a
|
|
|
|
:class:`~django.db.models.query.QuerySet`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
When Django deletes an object, by default it emulates the behavior of the SQL
|
|
|
|
constraint ``ON DELETE CASCADE`` -- in other words, any objects which had
|
|
|
|
foreign keys pointing at the object to be deleted will be deleted along with
|
|
|
|
it. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
b = Blog.objects.get(pk=1)
|
|
|
|
# This will delete the Blog and all of its Entry objects.
|
|
|
|
b.delete()
|
|
|
|
|
2010-11-10 00:46:42 +08:00
|
|
|
.. versionadded:: 1.3
|
|
|
|
This cascade behavior is customizable via the
|
|
|
|
:attr:`~django.db.models.ForeignKey.on_delete` argument to the
|
|
|
|
:class:`~django.db.models.ForeignKey`.
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Note that :meth:`~django.db.models.query.QuerySet.delete` is the only
|
|
|
|
:class:`~django.db.models.query.QuerySet` method that is not exposed on a
|
|
|
|
:class:`~django.db.models.Manager` itself. This is a safety mechanism to
|
|
|
|
prevent you from accidentally requesting ``Entry.objects.delete()``, and
|
|
|
|
deleting *all* the entries. If you *do* want to delete all the objects, then
|
|
|
|
you have to explicitly request a complete query set::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Entry.objects.all().delete()
|
|
|
|
|
2011-11-02 05:44:18 +08:00
|
|
|
.. _topics-db-queries-copy:
|
|
|
|
|
|
|
|
Copying model instances
|
|
|
|
=======================
|
|
|
|
|
|
|
|
Although there is no built-in method for copying model instances, it is
|
|
|
|
possible to easily create new instance with all fields' values copied. In the
|
|
|
|
simplest case, you can just set ``pk`` to ``None``. Using our blog example::
|
|
|
|
|
|
|
|
blog = Blog(name='My blog', tagline='Blogging is easy')
|
2012-08-23 22:46:38 +08:00
|
|
|
blog.save() # blog.pk == 1
|
2011-11-02 05:44:18 +08:00
|
|
|
|
|
|
|
blog.pk = None
|
2012-08-23 22:46:38 +08:00
|
|
|
blog.save() # blog.pk == 2
|
2011-11-02 05:44:18 +08:00
|
|
|
|
|
|
|
Things get more complicated if you use inheritance. Consider a subclass of
|
|
|
|
``Blog``::
|
|
|
|
|
|
|
|
class ThemeBlog(Blog):
|
|
|
|
theme = models.CharField(max_length=200)
|
|
|
|
|
|
|
|
django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme = 'python')
|
|
|
|
django_blog.save() # django_blog.pk == 3
|
|
|
|
|
|
|
|
Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::
|
|
|
|
|
|
|
|
django_blog.pk = None
|
|
|
|
django_blog.id = None
|
|
|
|
django_blog.save() # django_blog.pk == 4
|
|
|
|
|
|
|
|
This process does not copy related objects. If you want to copy relations,
|
|
|
|
you have to write a little bit more code. In our example, ``Entry`` has a many to many
|
|
|
|
field to ``Author``::
|
|
|
|
|
|
|
|
entry = Entry.objects.all()[0] # some previous entry
|
|
|
|
old_authors = entry.authors.all()
|
|
|
|
entry.pk = None
|
|
|
|
entry.save()
|
|
|
|
entry.authors = old_authors # saves new many2many relations
|
|
|
|
|
2009-03-11 15:06:50 +08:00
|
|
|
.. _topics-db-queries-update:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Updating multiple objects at once
|
|
|
|
=================================
|
|
|
|
|
|
|
|
Sometimes you want to set a field to a particular value for all the objects in
|
2012-03-03 00:45:06 +08:00
|
|
|
a :class:`~django.db.models.query.QuerySet`. You can do this with the
|
|
|
|
:meth:`~django.db.models.query.QuerySet.update` method. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
# Update all the headlines with pub_date in 2007.
|
|
|
|
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
|
|
|
|
fields using this method. To update a non-relation field, provide the new value
|
2012-03-03 01:16:52 +08:00
|
|
|
as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
|
2012-03-03 00:45:06 +08:00
|
|
|
new value to be the new model instance you want to point to. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> b = Blog.objects.get(pk=1)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
# Change every Entry so that it belongs to this Blog.
|
|
|
|
>>> Entry.objects.all().update(blog=b)
|
|
|
|
|
2010-01-11 02:36:45 +08:00
|
|
|
The ``update()`` method is applied instantly and returns the number of rows
|
2012-03-03 00:45:06 +08:00
|
|
|
affected by the query. The only restriction on the
|
|
|
|
:class:`~django.db.models.query.QuerySet` that is updated is that it can only
|
|
|
|
access one database table, the model's main table. You can filter based on
|
|
|
|
related fields, but you can only update columns in the model's main
|
|
|
|
table. Example::
|
2010-02-23 21:20:27 +08:00
|
|
|
|
|
|
|
>>> b = Blog.objects.get(pk=1)
|
|
|
|
|
|
|
|
# Update all the headlines belonging to this Blog.
|
|
|
|
>>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Be aware that the ``update()`` method is converted directly to an SQL
|
|
|
|
statement. It is a bulk operation for direct updates. It doesn't run any
|
2012-03-03 00:45:06 +08:00
|
|
|
:meth:`~django.db.models.Model.save` methods on your models, or emit the
|
|
|
|
``pre_save`` or ``post_save`` signals (which are a consequence of calling
|
2012-09-08 18:38:41 +08:00
|
|
|
:meth:`~django.db.models.Model.save`), or honor the
|
|
|
|
:attr:`~django.db.models.DateField.auto_now` field option.
|
|
|
|
If you want to save every item in a :class:`~django.db.models.query.QuerySet`
|
|
|
|
and make sure that the :meth:`~django.db.models.Model.save` method is called on
|
|
|
|
each instance, you don't need any special function to handle that. Just loop
|
|
|
|
over them and call :meth:`~django.db.models.Model.save`::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
for item in my_queryset:
|
|
|
|
item.save()
|
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
Calls to update can also use :ref:`F() objects <query-expressions>` to update
|
|
|
|
one field based on the value of another field in the model. This is especially
|
|
|
|
useful for incrementing counters based upon their current value. For example, to
|
|
|
|
increment the pingback count for every entry in the blog::
|
|
|
|
|
|
|
|
>>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
|
|
|
|
|
|
|
|
However, unlike ``F()`` objects in filter and exclude clauses, you can't
|
|
|
|
introduce joins when you use ``F()`` objects in an update -- you can only
|
|
|
|
reference fields local to the model being updated. If you attempt to introduce
|
|
|
|
a join with an ``F()`` object, a ``FieldError`` will be raised::
|
|
|
|
|
|
|
|
# THIS WILL RAISE A FieldError
|
|
|
|
>>> Entry.objects.update(headline=F('blog__name'))
|
|
|
|
|
2010-09-13 04:34:11 +08:00
|
|
|
.. _topics-db-queries-related:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Related objects
|
|
|
|
===============
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
When you define a relationship in a model (i.e., a
|
|
|
|
:class:`~django.db.models.ForeignKey`,
|
|
|
|
:class:`~django.db.models.OneToOneField`, or
|
|
|
|
:class:`~django.db.models.ManyToManyField`), instances of that model will have
|
2008-08-24 06:25:40 +08:00
|
|
|
a convenient API to access the related object(s).
|
|
|
|
|
|
|
|
Using the models at the top of this page, for example, an ``Entry`` object ``e``
|
|
|
|
can get its associated ``Blog`` object by accessing the ``blog`` attribute:
|
|
|
|
``e.blog``.
|
|
|
|
|
|
|
|
(Behind the scenes, this functionality is implemented by Python descriptors_.
|
|
|
|
This shouldn't really matter to you, but we point it out here for the curious.)
|
|
|
|
|
|
|
|
Django also creates API accessors for the "other" side of the relationship --
|
|
|
|
the link from the related model to the model that defines the relationship.
|
|
|
|
For example, a ``Blog`` object ``b`` has access to a list of all related
|
|
|
|
``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.
|
|
|
|
|
|
|
|
All examples in this section use the sample ``Blog``, ``Author`` and ``Entry``
|
|
|
|
models defined at the top of this page.
|
|
|
|
|
|
|
|
.. _descriptors: http://users.rcn.com/python/download/Descriptor.htm
|
|
|
|
|
|
|
|
One-to-many relationships
|
|
|
|
-------------------------
|
|
|
|
|
|
|
|
Forward
|
|
|
|
~~~~~~~
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
|
|
|
|
will have access to the related (foreign) object via a simple attribute of the
|
|
|
|
model.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
>>> e = Entry.objects.get(id=2)
|
|
|
|
>>> e.blog # Returns the related Blog object.
|
|
|
|
|
|
|
|
You can get and set via a foreign-key attribute. As you may expect, changes to
|
2012-03-03 00:45:06 +08:00
|
|
|
the foreign key aren't saved to the database until you call
|
2012-03-03 01:16:52 +08:00
|
|
|
:meth:`~django.db.models.Model.save`. Example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> e = Entry.objects.get(id=2)
|
|
|
|
>>> e.blog = some_blog
|
|
|
|
>>> e.save()
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e., it allows ``NULL``
|
2008-08-24 06:25:40 +08:00
|
|
|
values), you can assign ``None`` to it. Example::
|
|
|
|
|
|
|
|
>>> e = Entry.objects.get(id=2)
|
|
|
|
>>> e.blog = None
|
|
|
|
>>> e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
|
|
|
|
|
|
|
|
Forward access to one-to-many relationships is cached the first time the
|
|
|
|
related object is accessed. Subsequent accesses to the foreign key on the same
|
|
|
|
object instance are cached. Example::
|
|
|
|
|
|
|
|
>>> e = Entry.objects.get(id=2)
|
2012-04-29 00:02:01 +08:00
|
|
|
>>> print(e.blog) # Hits the database to retrieve the associated Blog.
|
|
|
|
>>> print(e.blog) # Doesn't hit the database; uses cached version.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Note that the :meth:`~django.db.models.query.QuerySet.select_related`
|
|
|
|
:class:`~django.db.models.query.QuerySet` method recursively prepopulates the
|
|
|
|
cache of all one-to-many relationships ahead of time. Example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> e = Entry.objects.select_related().get(id=2)
|
2012-04-29 00:02:01 +08:00
|
|
|
>>> print(e.blog) # Doesn't hit the database; uses cached version.
|
|
|
|
>>> print(e.blog) # Doesn't hit the database; uses cached version.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. _backwards-related-objects:
|
|
|
|
|
|
|
|
Following relationships "backward"
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
If a model has a :class:`~django.db.models.ForeignKey`, instances of the
|
|
|
|
foreign-key model will have access to a :class:`~django.db.models.Manager` that
|
|
|
|
returns all instances of the first model. By default, this
|
|
|
|
:class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the
|
|
|
|
source model name, lowercased. This :class:`~django.db.models.Manager` returns
|
|
|
|
``QuerySets``, which can be filtered and manipulated as described in the
|
|
|
|
"Retrieving objects" section above.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
>>> b = Blog.objects.get(id=1)
|
|
|
|
>>> b.entry_set.all() # Returns all Entry objects related to Blog.
|
|
|
|
|
|
|
|
# b.entry_set is a Manager that returns QuerySets.
|
|
|
|
>>> b.entry_set.filter(headline__contains='Lennon')
|
|
|
|
>>> b.entry_set.count()
|
|
|
|
|
|
|
|
You can override the ``FOO_set`` name by setting the ``related_name``
|
|
|
|
parameter in the ``ForeignKey()`` definition. For example, if the ``Entry``
|
|
|
|
model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the
|
|
|
|
above example code would look like this::
|
|
|
|
|
|
|
|
>>> b = Blog.objects.get(id=1)
|
|
|
|
>>> b.entries.all() # Returns all Entry objects related to Blog.
|
|
|
|
|
|
|
|
# b.entries is a Manager that returns QuerySets.
|
|
|
|
>>> b.entries.filter(headline__contains='Lennon')
|
|
|
|
>>> b.entries.count()
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
You cannot access a reverse :class:`~django.db.models.ForeignKey`
|
|
|
|
:class:`~django.db.models.Manager` from the class; it must be accessed from an
|
|
|
|
instance::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> Blog.entry_set
|
|
|
|
Traceback:
|
|
|
|
...
|
|
|
|
AttributeError: "Manager must be accessed via instance".
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
In addition to the :class:`~django.db.models.query.QuerySet` methods defined in
|
|
|
|
"Retrieving objects" above, the :class:`~django.db.models.ForeignKey`
|
|
|
|
:class:`~django.db.models.Manager` has additional methods used to handle the
|
|
|
|
set of related objects. A synopsis of each is below, and complete details can
|
|
|
|
be found in the :doc:`related objects reference </ref/models/relations>`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
``add(obj1, obj2, ...)``
|
|
|
|
Adds the specified model objects to the related object set.
|
|
|
|
|
|
|
|
``create(**kwargs)``
|
|
|
|
Creates a new object, saves it and puts it in the related object set.
|
|
|
|
Returns the newly created object.
|
|
|
|
|
|
|
|
``remove(obj1, obj2, ...)``
|
|
|
|
Removes the specified model objects from the related object set.
|
|
|
|
|
|
|
|
``clear()``
|
|
|
|
Removes all objects from the related object set.
|
|
|
|
|
|
|
|
To assign the members of a related set in one fell swoop, just assign to it
|
2009-06-18 21:32:48 +08:00
|
|
|
from any iterable object. The iterable can contain object instances, or just
|
2009-06-18 21:44:26 +08:00
|
|
|
a list of primary key values. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
b = Blog.objects.get(id=1)
|
|
|
|
b.entry_set = [e1, e2]
|
|
|
|
|
2009-06-18 21:32:48 +08:00
|
|
|
In this example, ``e1`` and ``e2`` can be full Entry instances, or integer
|
2009-06-18 21:44:26 +08:00
|
|
|
primary key values.
|
2009-06-18 21:32:48 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
If the ``clear()`` method is available, any pre-existing objects will be
|
|
|
|
removed from the ``entry_set`` before all objects in the iterable (in this
|
|
|
|
case, a list) are added to the set. If the ``clear()`` method is *not*
|
|
|
|
available, all objects in the iterable will be added without removing any
|
|
|
|
existing elements.
|
|
|
|
|
|
|
|
Each "reverse" operation described in this section has an immediate effect on
|
|
|
|
the database. Every addition, creation and deletion is immediately and
|
|
|
|
automatically saved to the database.
|
|
|
|
|
2011-09-12 03:28:18 +08:00
|
|
|
.. _m2m-reverse-relationships:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Many-to-many relationships
|
|
|
|
--------------------------
|
|
|
|
|
|
|
|
Both ends of a many-to-many relationship get automatic API access to the other
|
|
|
|
end. The API works just as a "backward" one-to-many relationship, above.
|
|
|
|
|
|
|
|
The only difference is in the attribute naming: The model that defines the
|
2012-03-03 00:45:06 +08:00
|
|
|
:class:`~django.db.models.ManyToManyField` uses the attribute name of that
|
|
|
|
field itself, whereas the "reverse" model uses the lowercased model name of the
|
|
|
|
original model, plus ``'_set'`` (just like reverse one-to-many relationships).
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
An example makes this easier to understand::
|
|
|
|
|
|
|
|
e = Entry.objects.get(id=3)
|
|
|
|
e.authors.all() # Returns all Author objects for this Entry.
|
|
|
|
e.authors.count()
|
|
|
|
e.authors.filter(name__contains='John')
|
|
|
|
|
|
|
|
a = Author.objects.get(id=5)
|
|
|
|
a.entry_set.all() # Returns all Entry objects for this Author.
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
Like :class:`~django.db.models.ForeignKey`,
|
|
|
|
:class:`~django.db.models.ManyToManyField` can specify ``related_name``. In the
|
|
|
|
above example, if the :class:`~django.db.models.ManyToManyField` in ``Entry``
|
|
|
|
had specified ``related_name='entries'``, then each ``Author`` instance would
|
|
|
|
have an ``entries`` attribute instead of ``entry_set``.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
One-to-one relationships
|
|
|
|
------------------------
|
|
|
|
|
2008-09-01 17:32:41 +08:00
|
|
|
One-to-one relationships are very similar to many-to-one relationships. If you
|
|
|
|
define a :class:`~django.db.models.OneToOneField` on your model, instances of
|
|
|
|
that model will have access to the related object via a simple attribute of the
|
|
|
|
model.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
class EntryDetail(models.Model):
|
|
|
|
entry = models.OneToOneField(Entry)
|
|
|
|
details = models.TextField()
|
|
|
|
|
|
|
|
ed = EntryDetail.objects.get(id=2)
|
|
|
|
ed.entry # Returns the related Entry object.
|
|
|
|
|
|
|
|
The difference comes in "reverse" queries. The related model in a one-to-one
|
|
|
|
relationship also has access to a :class:`~django.db.models.Manager` object, but
|
|
|
|
that :class:`~django.db.models.Manager` represents a single object, rather than
|
|
|
|
a collection of objects::
|
|
|
|
|
|
|
|
e = Entry.objects.get(id=2)
|
|
|
|
e.entrydetail # returns the related EntryDetail object
|
|
|
|
|
|
|
|
If no object has been assigned to this relationship, Django will raise
|
|
|
|
a ``DoesNotExist`` exception.
|
|
|
|
|
|
|
|
Instances can be assigned to the reverse relationship in the same way as
|
|
|
|
you would assign the forward relationship::
|
|
|
|
|
|
|
|
e.entrydetail = ed
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
How are the backward relationships possible?
|
|
|
|
--------------------------------------------
|
|
|
|
|
|
|
|
Other object-relational mappers require you to define relationships on both
|
|
|
|
sides. The Django developers believe this is a violation of the DRY (Don't
|
|
|
|
Repeat Yourself) principle, so Django only requires you to define the
|
|
|
|
relationship on one end.
|
|
|
|
|
|
|
|
But how is this possible, given that a model class doesn't know which other
|
|
|
|
model classes are related to it until those other model classes are loaded?
|
|
|
|
|
2012-03-03 00:45:06 +08:00
|
|
|
The answer lies in the :setting:`INSTALLED_APPS` setting. The first time any
|
|
|
|
model is loaded, Django iterates over every model in :setting:`INSTALLED_APPS`
|
|
|
|
and creates the backward relationships in memory as needed. Essentially, one of
|
|
|
|
the functions of :setting:`INSTALLED_APPS` is to tell Django the entire model
|
|
|
|
domain.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Queries over related objects
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
Queries involving related objects follow the same rules as queries involving
|
|
|
|
normal value fields. When specifying the value for a query to match, you may
|
|
|
|
use either an object instance itself, or the primary key value for the object.
|
|
|
|
|
|
|
|
For example, if you have a Blog object ``b`` with ``id=5``, the following
|
|
|
|
three queries would be identical::
|
|
|
|
|
|
|
|
Entry.objects.filter(blog=b) # Query using object instance
|
|
|
|
Entry.objects.filter(blog=b.id) # Query using id from instance
|
|
|
|
Entry.objects.filter(blog=5) # Query using id directly
|
|
|
|
|
|
|
|
Falling back to raw SQL
|
|
|
|
=======================
|
|
|
|
|
|
|
|
If you find yourself needing to write an SQL query that is too complex for
|
2009-12-20 10:46:58 +08:00
|
|
|
Django's database-mapper to handle, you can fall back on writing SQL by hand.
|
|
|
|
Django has a couple of options for writing raw SQL queries; see
|
2010-08-20 03:27:44 +08:00
|
|
|
:doc:`/topics/db/sql`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Finally, it's important to note that the Django database layer is merely an
|
|
|
|
interface to your database. You can access your database via other tools,
|
|
|
|
programming languages or database frameworks; there's nothing Django-specific
|
2008-09-29 12:09:39 +08:00
|
|
|
about your database.
|