2005-07-13 09:25:57 +08:00
|
|
|
======================
|
|
|
|
Database API reference
|
|
|
|
======================
|
|
|
|
|
2005-07-15 08:42:28 +08:00
|
|
|
Once you've created your `data models`_, you'll need to lookup data from the
|
|
|
|
database. This document explains the database abstraction API derived from the
|
|
|
|
models, and how to create, retrieve, and update objects.
|
|
|
|
|
|
|
|
.. _`data models`: http://www.djangoproject.com/documentation/model_api/
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
Throughout this reference, we'll refer to the following Poll application::
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
class Poll(meta.Model):
|
|
|
|
fields = (
|
|
|
|
meta.SlugField('slug', 'slug', unique_for_month='pub_date'),
|
|
|
|
meta.CharField('question', 'question', maxlength=255),
|
|
|
|
meta.DateTimeField('pub_date', 'date published'),
|
|
|
|
meta.DateTimeField('expire_date', 'expiration date'),
|
|
|
|
)
|
|
|
|
|
|
|
|
class Choice(meta.Model):
|
|
|
|
fields = (
|
2005-07-15 03:25:13 +08:00
|
|
|
meta.ForeignKey(Poll, edit_inline=True, edit_inline_type=meta.TABULAR,
|
|
|
|
num_in_admin=10, min_num_in_admin=5),
|
2005-07-13 09:25:57 +08:00
|
|
|
meta.CharField('choice', 'choice', maxlength=255, core=True),
|
|
|
|
meta.IntegerField('votes', 'votes', editable=False, default=0),
|
|
|
|
)
|
|
|
|
|
|
|
|
Basic lookup functions
|
|
|
|
======================
|
|
|
|
|
|
|
|
Each model exposes three basic functions for lookups: ``get_object``,
|
|
|
|
``get_list``, and ``get_count``. These functions all take the same arguments,
|
|
|
|
but ``get_object`` assumes that only a single record will be returned (and
|
2005-07-15 03:25:13 +08:00
|
|
|
raises ``AssertionError`` if that's not true), ``get_count`` simply returns a
|
|
|
|
count of objects matched by the lookup, and ``get_list`` returns a list of objects.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
Field lookups
|
|
|
|
=============
|
|
|
|
|
|
|
|
Basic field lookups take the form ``field__lookuptype`` (that's a
|
|
|
|
double-underscore). For example::
|
|
|
|
|
|
|
|
polls.get_list(pub_date__lte=datetime.datetime.now())
|
|
|
|
|
|
|
|
translates (roughly) into the following SQL:
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
SELECT * FROM polls_polls WHERE pub_date < NOW();
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
The DB API supports the following lookup types:
|
|
|
|
|
|
|
|
========== ==============================================================
|
|
|
|
Type Description
|
|
|
|
========== ==============================================================
|
2005-07-19 23:24:03 +08:00
|
|
|
exact Exact match: ``polls.get_object(id__exact=14)``.
|
2005-07-13 09:25:57 +08:00
|
|
|
iexact Case-insensitive exact match:
|
|
|
|
``polls.get_list(slug__iexact="foo")`` matches a slug of ``foo``,
|
|
|
|
``FOO``, ``fOo``, etc.
|
2005-07-15 03:25:13 +08:00
|
|
|
contains Case-sensitive containment test:
|
2005-07-13 09:25:57 +08:00
|
|
|
``polls.get_list(question__contains="spam")`` returns all polls
|
2005-07-19 23:24:03 +08:00
|
|
|
that contain "spam" in the question. (PostgreSQL only. MySQL
|
|
|
|
doesn't support case-sensitive LIKE statements; ``contains``
|
|
|
|
will act like ``icontains`` for MySQL.)
|
|
|
|
icontains Case-insensitive containment test.
|
|
|
|
gt Greater than: ``polls.get_list(id__gt=4)``.
|
|
|
|
gte Greater than or equal to.
|
|
|
|
lt Less than.
|
|
|
|
lte Less than or equal to.
|
2005-07-13 09:25:57 +08:00
|
|
|
startswith Case-sensitive starts-with:
|
2005-07-19 23:24:03 +08:00
|
|
|
``polls.get_list(question_startswith="Would")``. (PostgreSQL
|
|
|
|
only. MySQL doesn't support case-sensitive LIKE statements;
|
|
|
|
``startswith`` will act like ``istartswith`` for MySQL.)
|
|
|
|
endswith Case-sensitive ends-with. (PostgreSQL only. MySQL doesn't
|
|
|
|
support case-sensitive LIKE statements; ``endswith`` will act
|
|
|
|
like ``iendswith`` for MySQL.)
|
|
|
|
istartswith Case-insensitive starts-with.
|
|
|
|
iendswith Case-insensitive ends-with.
|
2005-07-13 09:25:57 +08:00
|
|
|
range Range test:
|
2005-07-15 03:25:13 +08:00
|
|
|
``polls.get_list(pub_date__range=(start_date, end_date))``
|
2005-07-13 09:25:57 +08:00
|
|
|
returns all polls with a pub_date between ``start_date``
|
|
|
|
and ``end_date`` (inclusive).
|
|
|
|
year For date/datetime fields, exact year match:
|
|
|
|
``polls.get_count(pub_date__year=2005)``.
|
|
|
|
month For date/datetime fields, exact month match.
|
|
|
|
day For date/datetime fields, exact day match.
|
|
|
|
isnull True/False; does is IF NULL/IF NOT NULL lookup:
|
|
|
|
``polls.get_list(expire_date__isnull=True)``.
|
|
|
|
========== ==============================================================
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
Multiple lookups are allowed, of course, and are translated as "AND"s::
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
polls.get_list(
|
|
|
|
pub_date__year=2005,
|
|
|
|
pub_date__month=1,
|
|
|
|
question__startswith="Would",
|
|
|
|
)
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
...retrieves all polls published in January 2005 that have a question starting with "Would."
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
Ordering
|
|
|
|
========
|
|
|
|
|
|
|
|
The results are automatically ordered by the ordering tuple given by the
|
|
|
|
``ordering`` key in the model, but the ordering may be explicitly
|
|
|
|
provided by the ``order_by`` argument to a lookup::
|
|
|
|
|
|
|
|
polls.get_list(
|
|
|
|
pub_date__year=2005,
|
|
|
|
pub_date__month=1,
|
|
|
|
order_by=(("pub_date", "DESC"), ("question", "ASC")),
|
|
|
|
)
|
|
|
|
|
|
|
|
The result set above will be ordered by ``pub_date`` (descending), then
|
|
|
|
by ``question`` (ascending). Just like in models, the ``order_by`` clause
|
|
|
|
is a list of ordering tuples where the first element is the field and the
|
2005-07-15 03:25:13 +08:00
|
|
|
second is "ASC" (ascending) or "DESC" (descending). You can also
|
2005-07-13 09:25:57 +08:00
|
|
|
use the tuple ``(None, "RANDOM")`` to order the result set randomly.
|
|
|
|
|
|
|
|
Relationships (joins)
|
|
|
|
=====================
|
|
|
|
|
|
|
|
Joins may implicitly be performed by following relationships:
|
|
|
|
``choices.get_list(poll__slug__exact="eggs")`` fetches a list of ``Choice``
|
|
|
|
objects where the associated ``Poll`` has a slug of ``eggs``. Multiple levels
|
|
|
|
of joins are allowed.
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
Given an instance of an object, related objects can be looked-up directly using
|
|
|
|
convenience functions. For example, if ``p`` is a ``Poll`` instance,
|
|
|
|
``p.get_choice_list()`` will return a list of all associated choices. Astute
|
2005-07-13 09:25:57 +08:00
|
|
|
readers will note that this is the same as
|
2005-07-15 03:25:13 +08:00
|
|
|
``choices.get_list(poll_id__exact=p.id)``, except clearer.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
Each type of relationship creates a set of methods on each object in the
|
2005-07-15 03:25:13 +08:00
|
|
|
relationship. These methods are created in both directions, so objects that are
|
2005-07-13 09:25:57 +08:00
|
|
|
"related-to" need not explicitly define reverse relationships; that happens
|
|
|
|
automatically.
|
|
|
|
|
|
|
|
One-to-one relations
|
|
|
|
--------------------
|
|
|
|
|
|
|
|
Each object in a one-to-one relationship will have a ``get_relatedobject()``
|
|
|
|
method. For example::
|
|
|
|
|
|
|
|
class Place(meta.Model):
|
|
|
|
fields = (
|
|
|
|
...
|
|
|
|
)
|
|
|
|
|
|
|
|
class Restaurant(meta.Model):
|
|
|
|
...
|
|
|
|
fields = (
|
2005-07-16 02:40:21 +08:00
|
|
|
meta.OneToOneField(places.Place),
|
2005-07-13 09:25:57 +08:00
|
|
|
...
|
|
|
|
)
|
|
|
|
|
|
|
|
In the above example, each ``Place`` will have a ``get_restaurant()`` method,
|
|
|
|
and each ``Restaurant`` will have a ``get_place()`` method.
|
|
|
|
|
|
|
|
Many-to-one relations
|
|
|
|
---------------------
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
In each many-to-one relationship, the related object will have a
|
2005-07-13 09:25:57 +08:00
|
|
|
``get_relatedobject()`` method, and the related-to object will have
|
|
|
|
``get_relatedobject()``, ``get_relatedobject_list()``, and
|
|
|
|
``get_relatedobject_count()`` methods (the same as the module-level
|
|
|
|
``get_object()``, ``get_list()``, and ``get_count()`` methods).
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
In the poll example above, here are the available choice methods on a ``Poll`` object ``p``::
|
|
|
|
|
|
|
|
p.get_choice()
|
|
|
|
p.get_choice_list()
|
|
|
|
p.get_choice_count()
|
|
|
|
|
|
|
|
And a ``Choice`` object ``c`` has the following method::
|
|
|
|
|
|
|
|
c.get_poll()
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
Many-to-many relations
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
Many-to-many relations result in the same set of methods as `Many-to-one relations`_,
|
2005-07-15 03:25:13 +08:00
|
|
|
except that the ``get_relatedobject_list()`` function on the related object will
|
2005-07-13 09:25:57 +08:00
|
|
|
return a list of instances instead of a single instance. So, if the relationship
|
2005-07-15 03:25:13 +08:00
|
|
|
between ``Poll`` and ``Choice`` was many-to-many, ``choice.get_poll_list()`` would
|
2005-07-13 09:25:57 +08:00
|
|
|
return a list.
|
|
|
|
|
|
|
|
Relationships across applications
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
If a relation spans applications -- if ``Place`` was had a ManyToOne relation to
|
|
|
|
a ``geo.City`` object, for example -- the name of the other application will be
|
|
|
|
added to the method, i.e. ``place.get_geo_city()`` and
|
|
|
|
``city.get_places_place_list()``.
|
|
|
|
|
|
|
|
Selecting related objects
|
|
|
|
-------------------------
|
|
|
|
|
|
|
|
Relations are the bread and butter of databases, so there's an option to "follow"
|
|
|
|
all relationships and pre-fill them in a simple cache so that later calls to
|
2005-07-15 03:25:13 +08:00
|
|
|
objects with a one-to-many relationship don't have to hit the database. Do this by
|
|
|
|
passing ``select_related=True`` to a lookup. This results in (sometimes much) larger
|
|
|
|
queries, but it means that later use of relationships is much faster.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
For example, using the Poll and Choice models from above, if you do the following::
|
|
|
|
|
|
|
|
c = choices.get_object(id__exact=5, select_related=True)
|
|
|
|
|
|
|
|
Then subsequent calls to ``c.get_poll()`` won't hit the database.
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
Note that ``select_related`` follows foreign keys as far as possible. If you have the
|
2005-07-15 05:04:21 +08:00
|
|
|
following models::
|
2005-07-15 03:25:13 +08:00
|
|
|
|
|
|
|
class Poll(meta.Model):
|
|
|
|
...
|
|
|
|
|
|
|
|
class Choice(meta.Model):
|
|
|
|
fields = (
|
|
|
|
meta.ForeignKey(Poll),
|
|
|
|
...
|
|
|
|
)
|
|
|
|
|
|
|
|
class SingleVote(meta.Model):
|
|
|
|
fields = (
|
|
|
|
meta.ForeignKey(Choice),
|
|
|
|
...
|
|
|
|
)
|
|
|
|
|
2005-07-15 05:04:21 +08:00
|
|
|
then a call to ``singlevotes.get_object(id__exact=4, select_related=True)`` will
|
|
|
|
cache the related choice *and* the related poll::
|
2005-07-15 03:25:13 +08:00
|
|
|
|
|
|
|
>>> sv = singlevotes.get_object(id__exact=4, select_related=True)
|
|
|
|
>>> c = sv.get_choice() # Doesn't hit the database.
|
|
|
|
>>> p = c.get_poll() # Doesn't hit the database.
|
|
|
|
|
|
|
|
>>> sv = singlevotes.get_object(id__exact=4) # Note no "select_related".
|
|
|
|
>>> c = sv.get_choice() # Hits the database.
|
|
|
|
>>> p = c.get_poll() # Hits the database.
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
Limiting selected rows
|
|
|
|
======================
|
|
|
|
|
|
|
|
The ``limit``, ``offset``, and ``distinct`` keywords can be used to control
|
|
|
|
which rows are returned. Both ``limit`` and ``offset`` should be integers which
|
|
|
|
will be directly passed to the SQL ``LIMIT``/``OFFSET`` commands.
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
If ``distinct`` is True, only distinct rows will be returned. This is equivalent
|
|
|
|
to a ``SELECT DISTINCT`` SQL clause.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
Other lookup options
|
|
|
|
====================
|
|
|
|
|
|
|
|
There are a few other ways of more directly controlling the generated SQL
|
|
|
|
for the lookup. Note that by definition these extra lookups may not be
|
2005-07-15 03:25:13 +08:00
|
|
|
portable to different database engines (because you're explicitly writing
|
|
|
|
SQL code) and should be avoided if possible.:
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
``params``
|
|
|
|
----------
|
|
|
|
|
|
|
|
All the extra-SQL params described below may use standard Python string
|
|
|
|
formatting codes to indicate parameters that the database engine will
|
|
|
|
automatically quote. The ``params`` argument can contain any extra
|
|
|
|
parameters to be substituted.
|
|
|
|
|
|
|
|
``select``
|
|
|
|
----------
|
|
|
|
|
|
|
|
The ``select`` keyword allows you to select extra fields. This should be a
|
2005-07-15 03:25:13 +08:00
|
|
|
dictionary mapping attribute names to a SQL clause to use to calculate that
|
|
|
|
attribute. For example::
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
polls.get_list(
|
|
|
|
select={
|
2005-07-15 03:25:13 +08:00
|
|
|
'choice_count': 'SELECT COUNT(*) FROM choices WHERE poll_id = polls.id'
|
2005-07-13 09:25:57 +08:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
Each of the resulting ``Poll`` objects will have an extra attribute, ``choice_count``,
|
|
|
|
an integer count of associated ``Choice`` objects. Note that the parenthesis required by
|
2005-07-13 09:25:57 +08:00
|
|
|
most database engines around sub-selects are not required in Django's ``select``
|
|
|
|
clauses.
|
|
|
|
|
|
|
|
``where`` / ``tables``
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
If you need to explicitly pass extra ``WHERE`` clauses -- perhaps to perform
|
2005-07-15 03:25:13 +08:00
|
|
|
non-explicit joins -- use the ``where`` keyword. If you need to
|
2005-07-13 09:25:57 +08:00
|
|
|
join other tables into your query, you can pass their names to ``tables``.
|
|
|
|
|
2005-07-15 03:25:13 +08:00
|
|
|
``where`` and ``tables`` both take a list of strings. All ``where`` parameters
|
|
|
|
are "AND"ed to any other search criteria.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
polls.get_list(question__startswith='Who', where=['id IN (3, 4, 5, 20)'])
|
|
|
|
|
|
|
|
...translates (roughly) into the following SQL:
|
|
|
|
|
|
|
|
SELECT * FROM polls_polls WHERE question LIKE 'Who%' AND id IN (3, 4, 5, 20);
|
|
|
|
|
2005-07-15 08:42:28 +08:00
|
|
|
Changing objects
|
|
|
|
================
|
|
|
|
|
2005-07-16 02:40:21 +08:00
|
|
|
Once you've retrieved an object from the database using any of the above
|
2005-07-15 08:42:28 +08:00
|
|
|
options, changing it is extremely easy. Make changes directly to the
|
|
|
|
objects fields, then call the object's ``save()`` method::
|
|
|
|
|
|
|
|
>>> p = polls.get_object(id__exact=15)
|
|
|
|
>>> p.slug = "new_slug"
|
|
|
|
>>> p.pub_date = datetime.datetime.now()
|
|
|
|
>>> p.save()
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
Creating new objects
|
|
|
|
====================
|
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
Creating new objects (i.e. ``INSERT``) is done by creating new instances
|
|
|
|
of objects then calling save() on them::
|
|
|
|
|
2005-07-19 23:24:03 +08:00
|
|
|
>>> p = polls.Poll(id=None,
|
2005-07-16 04:37:03 +08:00
|
|
|
... slug="eggs",
|
|
|
|
... question="How do you like your eggs?",
|
|
|
|
... pub_date=datetime.datetime.now(),
|
|
|
|
... expire_date=some_future_date)
|
|
|
|
>>> p.save()
|
2005-07-19 23:24:03 +08:00
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
Calling ``save()`` on an object with an id if ``None`` signifies to
|
|
|
|
Django that the object is new and should be inserted.
|
|
|
|
|
|
|
|
Related objects (i.e. ``Choices``) are created using convience functions::
|
|
|
|
|
|
|
|
>>> p.add_choice(choice="Over easy", votes=0)
|
|
|
|
>>> p.add_choice(choice="Scrambled", votes=0)
|
|
|
|
>>> p.add_choice(choice="Fertilized", votes=0)
|
|
|
|
>>> p.add_choice(choice="Poached", votes=0)
|
|
|
|
>>> p.get_choice_count()
|
|
|
|
4
|
2005-07-19 23:24:03 +08:00
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
Each of those ``add_choice`` methods is equivilent to (except obviously much
|
|
|
|
simpler than)::
|
|
|
|
|
|
|
|
>>> c = polls.Choice(id=None,
|
|
|
|
... poll_id=p.id,
|
|
|
|
... choice="Over easy",
|
|
|
|
... votes=0)
|
|
|
|
>>> c.save()
|
2005-07-19 23:24:03 +08:00
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
Note that when using the `add_foo()`` methods, you do not give any value
|
2005-07-19 23:24:03 +08:00
|
|
|
for the ``id`` field, nor do you give a value for the field that stores
|
2005-07-16 04:37:03 +08:00
|
|
|
the relation (``poll_id`` in this case).
|
|
|
|
|
|
|
|
Deleting objects
|
|
|
|
================
|
|
|
|
|
|
|
|
Just cause we're crazy like that, the delete method is named ``delete()``.
|
|
|
|
Yeah, you never know what we're going to do next.
|
|
|
|
|