2005-07-13 01:25:57 +00:00
===============
Model reference
===============
2005-08-26 18:29:11 +00:00
A model is the single, definitive source of data about your data. It contains
the essential fields and behaviors of the data you're storing. Generally, each
model maps to a single database table.
2005-07-13 01:25:57 +00:00
2005-08-26 18:29:11 +00:00
The basics:
2005-07-13 01:25:57 +00:00
2006-05-02 01:31:56 +00:00
* Each model is a Python class that subclasses ``django.db.models.Model``.
2005-08-26 18:29:11 +00:00
* Each attribute of the model represents a database field.
2006-05-02 01:31:56 +00:00
* Model metadata (non-field information) goes in an inner class named
``Meta``.
* With all of this, Django gives you an automatically-generated
database-access API, which is explained in the `Database API reference`_.
2005-08-25 22:51:30 +00:00
2005-08-26 18:29:11 +00:00
A companion to this document is the `official repository of model examples`_.
2006-05-05 02:57:19 +00:00
(In the Django source distribution, these examples are in the
``tests/modeltests`` directory.)
2005-08-25 22:51:30 +00:00
2007-04-13 01:19:44 +00:00
.. _Database API reference: ../db-api/
2007-08-05 04:42:26 +00:00
.. _official repository of model examples: ../models/
2005-07-13 01:25:57 +00:00
2006-05-02 01:31:56 +00:00
Quick example
2005-08-26 18:29:11 +00:00
=============
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
This example model defines a ``Person``, which has a ``first_name`` and
``last_name``::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
from django.db import models
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Person(models.Model):
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
``first_name`` and ``last_name`` are *fields* of the model. Each field is
specified as a class attribute, and each attribute maps to a database column.
2005-07-17 04:20:57 +00:00
2006-05-04 04:59:45 +00:00
The above ``Person`` model would create a database table like this::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
2005-07-17 04:20:57 +00:00
2006-05-04 04:59:45 +00:00
Some technical notes:
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
* The name of the table, ``myapp_person``, is automatically derived from
2007-11-29 18:15:38 +00:00
some model metadata but can be overridden. See `Table names`_ below.
2006-05-02 01:31:56 +00:00
* An ``id`` field is added automatically, but this behavior can be
2008-04-27 11:55:47 +00:00
overridden. See `Automatic primary key fields`_ below.
2006-05-02 01:31:56 +00:00
* The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
syntax, but it's worth noting Django uses SQL tailored to the database
backend specified in your `settings file`_.
2005-11-14 01:44:35 +00:00
2007-04-13 01:19:44 +00:00
.. _settings file: ../settings/
2005-11-14 01:44:35 +00:00
2006-05-02 01:31:56 +00:00
Fields
======
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
The most important part of a model -- and the only required part of a model --
is the list of database fields it defines. Fields are specified by class
attributes.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Example::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Musician(models.Model):
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Album(models.Model):
artist = models.ForeignKey(Musician)
2007-08-05 05:14:46 +00:00
name = models.CharField(max_length=100)
2006-05-02 01:31:56 +00:00
release_date = models.DateField()
num_stars = models.IntegerField()
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Field name restrictions
-----------------------
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Django places only two restrictions on model field names:
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
1. A field name cannot be a Python reserved word, because that would result
in a Python syntax error. For example::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Example(models.Model):
pass = models.IntegerField() # 'pass' is a reserved word!
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
2. A field name cannot contain more than one underscore in a row, due to
the way Django's query lookup syntax works. For example::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Example(models.Model):
2007-01-03 14:29:21 +00:00
foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
These limitations can be worked around, though, because your field name doesn't
necessarily have to match your database column name. See `db_column`_ below.
2005-07-17 04:20:57 +00:00
2006-05-02 01:59:39 +00:00
SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
2006-05-02 01:31:56 +00:00
model field names, because Django escapes all database table names and column
names in every underlying SQL query. It uses the quoting syntax of your
particular database engine.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Field types
-----------
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Each field in your model should be an instance of the appropriate ``Field``
class. Django uses the field class types to determine a few things:
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
* The database column type (e.g. ``INTEGER``, ``VARCHAR``).
* The widget to use in Django's admin interface, if you care to use it
(e.g. ``<input type="text">``, ``<select>``).
* The minimal validation requirements, used in Django's admin and in
2008-07-27 23:23:49 +00:00
automatically-generated forms.
2005-12-09 01:53:30 +00:00
2006-05-02 01:31:56 +00:00
Here are all available field types:
2005-12-09 01:53:30 +00:00
2006-05-02 01:31:56 +00:00
``AutoField``
~~~~~~~~~~~~~
2005-12-09 01:53:30 +00:00
2006-05-02 01:31:56 +00:00
An ``IntegerField`` that automatically increments according to available IDs.
You usually won't need to use this directly; a primary key field will
automatically be added to your model if you don't specify otherwise. See
2006-05-09 15:21:28 +00:00
`Automatic primary key fields`_.
2005-12-09 01:53:30 +00:00
2006-05-02 01:31:56 +00:00
``BooleanField``
~~~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
A true/false field.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as a checkbox.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
``CharField``
~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
A string field, for small- to large-sized strings.
2005-11-14 01:44:35 +00:00
2006-05-02 01:31:56 +00:00
For large amounts of text, use ``TextField``.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` (a single-line input).
2005-07-17 04:20:57 +00:00
2007-08-05 05:14:46 +00:00
``CharField`` has an extra required argument, ``max_length``, the maximum length
(in characters) of the field. The max_length is enforced at the database level
2006-05-02 01:31:56 +00:00
and in Django's validation.
2005-07-17 04:20:57 +00:00
2007-08-05 05:14:46 +00:00
Django veterans: Note that the argument is now called ``max_length`` to
provide consistency throughout Django. There is full legacy support for
2007-09-12 13:11:51 +00:00
the old ``maxlength`` argument, but ``max_length`` is preferred.
2007-10-20 12:35:10 +00:00
2007-08-07 02:33:11 +00:00
``CommaSeparatedIntegerField``
2006-05-02 01:31:56 +00:00
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2007-08-05 05:14:46 +00:00
A field of integers separated by commas. As in ``CharField``, the ``max_length``
2006-05-02 01:31:56 +00:00
argument is required.
2005-07-13 01:25:57 +00:00
2006-05-02 01:31:56 +00:00
``DateField``
~~~~~~~~~~~~~
2005-07-19 17:20:37 +00:00
2006-05-02 01:31:56 +00:00
A date field. Has a few extra optional arguments:
2005-07-13 01:25:57 +00:00
2006-05-02 01:31:56 +00:00
====================== ===================================================
Argument Description
====================== ===================================================
``auto_now`` Automatically set the field to now every time the
object is saved. Useful for "last-modified"
2006-06-01 04:37:47 +00:00
timestamps. Note that the current date is *always*
used; it's not just a default value that you can
override.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``auto_now_add`` Automatically set the field to now when the object
is first created. Useful for creation of
2006-06-01 04:37:47 +00:00
timestamps. Note that the current date is *always*
used; it's not just a default value that you can
override.
2006-05-02 01:31:56 +00:00
====================== ===================================================
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` with a JavaScript
2007-09-15 18:33:03 +00:00
calendar, and a shortcut for "Today." The JavaScript calendar will always start
the week on a Sunday.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``DateTimeField``
~~~~~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A date and time field. Takes the same extra options as ``DateField``.
2005-07-13 01:25:57 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as two ``<input type="text">`` fields, with
JavaScript shortcuts.
2005-08-26 18:29:11 +00:00
2007-05-21 01:29:58 +00:00
``DecimalField``
2007-05-21 20:45:33 +00:00
~~~~~~~~~~~~~~~~
**New in Django development version**
2007-05-21 01:29:58 +00:00
A fixed-precision decimal number, represented in Python by a ``Decimal`` instance.
Has two **required** arguments:
====================== ===================================================
Argument Description
====================== ===================================================
``max_digits`` The maximum number of digits allowed in the number.
``decimal_places`` The number of decimal places to store with the
number.
====================== ===================================================
For example, to store numbers up to 999 with a resolution of 2 decimal places,
you'd use::
models.DecimalField(..., max_digits=5, decimal_places=2)
And to store numbers up to approximately one billion with a resolution of 10
decimal places::
models.DecimalField(..., max_digits=19, decimal_places=10)
The admin represents this as an ``<input type="text">`` (a single-line input).
2006-05-02 01:31:56 +00:00
``EmailField``
~~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A ``CharField`` that checks that the value is a valid e-mail address.
2007-09-14 19:22:43 +00:00
In Django 0.96, this doesn't accept ``max_length``; its ``max_length`` is
automatically set to 75. In the Django development version, ``max_length`` is
set to 75 by default, but you can specify it to override default behavior.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``FileField``
~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2007-04-25 06:38:23 +00:00
A file-upload field. Has one **required** argument:
2005-08-26 18:29:11 +00:00
2007-04-25 06:38:23 +00:00
====================== ===================================================
Argument Description
====================== ===================================================
``upload_to`` A local filesystem path that will be appended to
your ``MEDIA_ROOT`` setting to determine the
output of the ``get_<fieldname>_url()`` helper
function.
====================== ===================================================
This path may contain `strftime formatting`_, which will be replaced by the
date/time of the file upload (so that uploaded files don't fill up the given
directory).
2005-08-26 18:29:11 +00:00
2007-04-25 06:38:23 +00:00
The admin represents this field as an ``<input type="file">`` (a file-upload
widget).
2005-10-20 13:22:20 +00:00
2006-05-02 01:31:56 +00:00
Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few
steps:
2005-10-20 13:22:20 +00:00
2006-05-02 01:31:56 +00:00
1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
2006-05-22 05:04:40 +00:00
full path to a directory where you'd like Django to store uploaded
files. (For performance, these files are not stored in the database.)
Define ``MEDIA_URL`` as the base public URL of that directory. Make
sure that this directory is writable by the Web server's user
account.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
2. Add the ``FileField`` or ``ImageField`` to your model, making sure
2006-05-22 05:04:40 +00:00
to define the ``upload_to`` option to tell Django to which
subdirectory of ``MEDIA_ROOT`` it should upload files.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
3. All that will be stored in your database is a path to the file
2006-08-20 05:32:20 +00:00
(relative to ``MEDIA_ROOT``). You'll most likely want to use the
2006-05-22 05:04:40 +00:00
convenience ``get_<fieldname>_url`` function provided by Django. For
example, if your ``ImageField`` is called ``mug_shot``, you can get
the absolute URL to your image in a template with ``{{
object.get_mug_shot_url }}``.
2005-08-26 18:29:11 +00:00
2006-08-08 15:03:01 +00:00
For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and
``upload_to`` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'`` part of
``upload_to`` is strftime formatting; ``'%Y'`` is the four-digit year,
``'%m'`` is the two-digit month and ``'%d'`` is the two-digit day. If you
upload a file on Jan. 15, 2007, it will be saved in the directory
``/home/media/photos/2007/01/15``.
2007-05-27 13:01:21 +00:00
If you want to retrieve the upload file's on-disk filename, or a URL that
refers to that file, or the file's size, you can use the
``get_FOO_filename()``, ``get_FOO_url()`` and ``get_FOO_size()`` methods.
They are all documented here__.
__ ../db-api/#get-foo-filename
2006-08-14 23:07:43 +00:00
Note that whenever you deal with uploaded files, you should pay close attention
to where you're uploading them and what type of files they are, to avoid
security holes. *Validate all uploaded files* so that you're sure the files are
what you think they are. For example, if you blindly let somebody upload files,
without validation, to a directory that's within your Web server's document
root, then somebody could upload a CGI or PHP script and execute that script by
visiting its URL on your site. Don't allow that.
2006-05-02 01:31:56 +00:00
.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
2005-07-17 04:20:57 +00:00
2007-09-20 01:48:47 +00:00
**New in development version:** By default, ``FileField`` instances are
created as ``varchar(100)`` columns in your database. As with other fields, you
can change the maximum length using the ``max_length`` argument.
2007-09-19 23:33:57 +00:00
2006-05-02 01:31:56 +00:00
``FilePathField``
~~~~~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A field whose choices are limited to the filenames in a certain directory
on the filesystem. Has three special arguments, of which the first is
2007-04-25 06:38:23 +00:00
**required**:
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
====================== ===================================================
Argument Description
====================== ===================================================
``path`` Required. The absolute filesystem path to a
directory from which this ``FilePathField`` should
get its choices. Example: ``"/home/images"``.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
``match`` Optional. A regular expression, as a string, that
``FilePathField`` will use to filter filenames.
Note that the regex will be applied to the
base filename, not the full path. Example:
2007-09-08 19:30:16 +00:00
``"foo.*\.txt$"``, which will match a file called
2006-05-02 01:31:56 +00:00
``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``recursive`` Optional. Either ``True`` or ``False``. Default is
``False``. Specifies whether all subdirectories of
``path`` should be included.
====================== ===================================================
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Of course, these arguments can be used together.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
The one potential gotcha is that ``match`` applies to the base filename,
not the full path. So, this example::
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
FilePathField(path="/home/images", match="foo.*", recursive=True)
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
because the ``match`` applies to the base filename (``foo.gif`` and
``bar.gif``).
2005-07-17 04:20:57 +00:00
2007-09-20 01:48:47 +00:00
**New in development version:** By default, ``FilePathField`` instances are
created as ``varchar(100)`` columns in your database. As with other fields, you
can change the maximum length using the ``max_length`` argument.
2007-09-19 23:33:57 +00:00
2006-05-02 01:31:56 +00:00
``FloatField``
~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2007-05-21 20:45:33 +00:00
**Changed in Django development version**
2007-05-21 01:29:58 +00:00
A floating-point number represented in Python by a ``float`` instance.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` (a single-line input).
2005-08-26 18:29:11 +00:00
2007-05-21 20:45:33 +00:00
**NOTE:** The semantics of ``FloatField`` have changed in the Django
development version. See the `Django 0.96 documentation`_ for the old behavior.
.. _Django 0.96 documentation: http://www.djangoproject.com/documentation/0.96/model-api/#floatfield
2006-05-02 01:31:56 +00:00
``ImageField``
~~~~~~~~~~~~~~
2005-10-10 14:00:20 +00:00
2007-08-25 18:48:32 +00:00
Like `FileField`_, but validates that the uploaded object is a valid
2006-05-02 01:31:56 +00:00
image. Has two extra optional arguments, ``height_field`` and
``width_field``, which, if set, will be auto-populated with the height and
width of the image each time a model instance is saved.
2005-10-10 14:00:20 +00:00
2007-05-27 13:01:21 +00:00
In addition to the special ``get_FOO_*`` methods that are available for
``FileField``, an ``ImageField`` also has ``get_FOO_height()`` and
``get_FOO_width()`` methods. These are documented elsewhere_.
2006-05-02 01:31:56 +00:00
Requires the `Python Imaging Library`_.
2005-10-10 14:00:20 +00:00
2006-05-02 01:31:56 +00:00
.. _Python Imaging Library: http://www.pythonware.com/products/pil/
2007-05-27 13:01:21 +00:00
.. _elsewhere: ../db-api/#get-foo-height-and-get-foo-width
2005-09-30 13:49:43 +00:00
2007-09-20 01:48:47 +00:00
**New in development version:** By default, ``ImageField`` instances are
created as ``varchar(100)`` columns in your database. As with other fields, you
can change the maximum length using the ``max_length`` argument.
2007-09-19 23:33:57 +00:00
2006-05-02 01:31:56 +00:00
``IntegerField``
~~~~~~~~~~~~~~~~
2005-10-10 14:00:20 +00:00
2006-05-02 01:31:56 +00:00
An integer.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` (a single-line input).
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
``IPAddressField``
~~~~~~~~~~~~~~~~~~
2005-10-12 04:14:21 +00:00
2008-02-15 11:38:53 +00:00
An IP address, in string format (e.g. "192.0.2.30").
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` (a single-line input).
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
``NullBooleanField``
~~~~~~~~~~~~~~~~~~~~
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this
instead of a ``BooleanField`` with ``null=True``.
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
``PhoneNumberField``
~~~~~~~~~~~~~~~~~~~~
2005-10-12 04:14:21 +00:00
2006-05-02 01:31:56 +00:00
A ``CharField`` that checks that the value is a valid U.S.A.-style phone
number (in the format ``XXX-XXX-XXXX``).
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
``PositiveIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Like an ``IntegerField``, but must be positive.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
``PositiveSmallIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Like a ``PositiveIntegerField``, but only allows values under a certain
(database-dependent) point.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
``SlugField``
~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
"Slug" is a newspaper term. A slug is a short label for something,
containing only letters, numbers, underscores or hyphens. They're generally
used in URLs.
2005-07-17 04:20:57 +00:00
2007-08-05 05:14:46 +00:00
Like a CharField, you can specify ``max_length``. If ``max_length`` is
2007-03-23 20:45:30 +00:00
not specified, Django will use a default length of 50.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Implies ``db_index=True``.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``SmallIntegerField``
~~~~~~~~~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Like an ``IntegerField``, but only allows values under a certain
(database-dependent) point.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``TextField``
~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A large text field.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as a ``<textarea>`` (a multi-line input).
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``TimeField``
~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A time. Accepts the same auto-population options as ``DateField`` and
``DateTimeField``.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` with some
JavaScript shortcuts.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``URLField``
~~~~~~~~~~~~
2006-02-17 18:15:07 +00:00
2006-05-02 01:31:56 +00:00
A field for a URL. If the ``verify_exists`` option is ``True`` (default),
the URL given will be checked for existence (i.e., the URL actually loads
and doesn't give a 404 response).
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` (a single-line input).
2005-08-26 18:29:11 +00:00
2007-08-05 05:14:46 +00:00
``URLField`` takes an optional argument, ``max_length``, the maximum length (in
characters) of the field. The maximum length is enforced at the database level and
in Django's validation. If you don't specify ``max_length``, a default of 200
2007-06-11 11:19:43 +00:00
is used.
2006-05-02 01:31:56 +00:00
``USStateField``
~~~~~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A two-letter U.S. state abbreviation.
2005-11-06 22:53:07 +00:00
2006-05-02 01:31:56 +00:00
The admin represents this as an ``<input type="text">`` (a single-line input).
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``XMLField``
~~~~~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A ``TextField`` that checks that the value is valid XML that matches a
given schema. Takes one required argument, ``schema_path``, which is the
filesystem path to a RelaxNG_ schema against which to validate the field.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
.. _RelaxNG: http://www.relaxng.org/
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Field options
-------------
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
The following arguments are available to all field types. All are optional.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
``null``
~~~~~~~~
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
If ``True``, Django will store empty values as ``NULL`` in the database.
Default is ``False``.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Note that empty string values will always get stored as empty strings, not
2007-05-26 09:17:38 +00:00
as ``NULL``. Only use ``null=True`` for non-string fields such as integers,
booleans and dates. For both types of fields, you will also need to set
``blank=True`` if you wish to permit empty values in forms, as the ``null``
parameter only affects database storage (see blank_, below).
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Avoid using ``null`` on string-based fields such as ``CharField`` and
``TextField`` unless you have an excellent reason. If a string-based field
has ``null=True``, that means it has two possible values for "no data":
``NULL``, and the empty string. In most cases, it's redundant to have two
possible values for "no data;" Django convention is to use the empty
string, not ``NULL``.
2005-08-26 18:29:11 +00:00
2007-06-23 14:16:00 +00:00
.. note::
2007-06-30 20:58:36 +00:00
When using the Oracle database backend, the ``null=True`` option will
be coerced for string-based fields that can blank, and the value
``NULL`` will be stored to denote the empty string.
2007-06-23 14:16:00 +00:00
2006-05-02 01:31:56 +00:00
``blank``
~~~~~~~~~
2007-05-08 03:20:49 +00:00
If ``True``, the field is allowed to be blank. Default is ``False``.
2006-05-02 01:31:56 +00:00
Note that this is different than ``null``. ``null`` is purely
database-related, whereas ``blank`` is validation-related. If a field has
``blank=True``, validation on Django's admin site will allow entry of an
empty value. If a field has ``blank=False``, the field will be required.
``choices``
~~~~~~~~~~~
2006-06-07 02:46:08 +00:00
An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
field.
2006-05-02 01:31:56 +00:00
If this is given, Django's admin will use a select box instead of the
standard text field and will limit choices to the choices given.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
A choices list looks like this::
YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
('GR', 'Graduate'),
)
The first element in each tuple is the actual value to be stored. The
second element is the human-readable name for the option.
The choices list can be defined either as part of your model class::
class Foo(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
2007-08-05 05:14:46 +00:00
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
2006-05-02 01:31:56 +00:00
or outside your model class altogether::
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Foo(models.Model):
2007-08-05 05:14:46 +00:00
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
2006-05-02 01:31:56 +00:00
2008-07-19 07:53:02 +00:00
You can also collect your available choices into named groups that can
be used for organizational purposes::
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
The first element in each tuple is the name to apply to the group. The
second element is an iterable of 2-tuples, with each 2-tuple containing
a value and a human-readable name for an option. Grouped options may be
combined with ungrouped options within a single list (such as the
`unknown` option in this example).
2007-02-26 21:52:22 +00:00
For each model field that has ``choices`` set, Django will add a method to
retrieve the human-readable name for the field's current value. See
`get_FOO_display`_ in the database API documentation.
2007-02-26 21:40:15 +00:00
2007-04-13 01:19:44 +00:00
.. _get_FOO_display: ../db-api/#get-foo-display
2007-02-26 21:40:15 +00:00
2006-06-07 02:46:08 +00:00
Finally, note that choices can be any iterable object -- not necessarily a
list or tuple. This lets you construct choices dynamically. But if you find
yourself hacking ``choices`` to be dynamic, you're probably better off using
a proper database table with a ``ForeignKey``. ``choices`` is meant for static
data that doesn't change much, if ever.
2006-05-02 01:31:56 +00:00
``core``
~~~~~~~~
For objects that are edited inline to a related object.
In the Django admin, if all "core" fields in an inline-edited object are
cleared, the object will be deleted.
It is an error to have an inline-editable relation without at least one
``core=True`` field.
2006-06-01 04:35:44 +00:00
Please note that each field marked "core" is treated as a required field by the
Django admin site. Essentially, this means you should put ``core=True`` on all
required fields in your related object that is being edited inline.
2006-05-02 01:31:56 +00:00
``db_column``
~~~~~~~~~~~~~
The name of the database column to use for this field. If this isn't given,
Django will use the field's name.
If your database column name is an SQL reserved word, or contains
characters that aren't allowed in Python variable names -- notably, the
hyphen -- that's OK. Django quotes column and table names behind the
scenes.
``db_index``
~~~~~~~~~~~~
If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
statement for this field.
2007-06-23 14:16:00 +00:00
``db_tablespace``
~~~~~~~~~~~~~~~~~
2007-06-30 20:58:36 +00:00
**New in Django development version**
The name of the database tablespace to use for this field's index, if
2007-12-04 06:13:56 +00:00
this field is indexed. The default is the project's
2007-12-01 19:23:49 +00:00
``DEFAULT_INDEX_TABLESPACE`` setting, if set, or the ``db_tablespace``
of the model, if any. If the backend doesn't support tablespaces, this
2007-06-30 20:58:36 +00:00
option is ignored.
2007-06-23 14:16:00 +00:00
2006-05-02 01:31:56 +00:00
``default``
~~~~~~~~~~~
2008-03-20 06:56:23 +00:00
The default value for the field. This can be a value or a callable object. If
callable it will be called every time a new object is created.
2006-05-02 01:31:56 +00:00
``editable``
~~~~~~~~~~~~
2008-07-27 23:23:49 +00:00
If ``False``, the field will not be editable in the admin or via forms
automatically generated from the model class. Default is ``True``.
2006-05-02 01:31:56 +00:00
``help_text``
~~~~~~~~~~~~~
Extra "help" text to be displayed under the field on the object's admin
form. It's useful for documentation even if your object doesn't have an
admin form.
2007-08-06 05:33:18 +00:00
Note that this value is *not* HTML-escaped when it's displayed in the admin
interface. This lets you include HTML in ``help_text`` if you so desire. For
example::
2008-07-29 12:41:08 +00:00
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
2007-08-06 05:33:18 +00:00
2008-07-25 14:47:35 +00:00
Alternatively you can use plain text and
``django.utils.html.escape()`` to escape any HTML special characters.
2006-05-02 01:31:56 +00:00
``primary_key``
~~~~~~~~~~~~~~~
If ``True``, this field is the primary key for the model.
If you don't specify ``primary_key=True`` for any fields in your model,
Django will automatically add this field::
id = models.AutoField('ID', primary_key=True)
Thus, you don't need to set ``primary_key=True`` on any of your fields
unless you want to override the default primary-key behavior.
2008-06-20 12:10:13 +00:00
``primary_key=True`` implies ``null=False`` and ``unique=True``. Only
one primary key is allowed on an object.
2006-05-02 01:31:56 +00:00
``unique``
~~~~~~~~~~
If ``True``, this field must be unique throughout the table.
2007-10-20 12:35:10 +00:00
This is enforced at the database level and at the Django admin-form level. If
2008-06-16 04:04:24 +00:00
you try to save a model with a duplicate value in a ``unique`` field, a
2007-10-20 12:35:10 +00:00
``django.db.IntegrityError`` will be raised by the model's ``save()`` method.
2006-05-02 01:31:56 +00:00
``unique_for_date``
~~~~~~~~~~~~~~~~~~~
Set this to the name of a ``DateField`` or ``DateTimeField`` to require
that this field be unique for the value of the date field.
For example, if you have a field ``title`` that has
``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
two records with the same ``title`` and ``pub_date``.
This is enforced at the Django admin-form level but not at the database level.
``unique_for_month``
~~~~~~~~~~~~~~~~~~~~
Like ``unique_for_date``, but requires the field to be unique with respect
to the month.
``unique_for_year``
~~~~~~~~~~~~~~~~~~~
Like ``unique_for_date`` and ``unique_for_month``.
``validator_list``
~~~~~~~~~~~~~~~~~~
A list of extra validators to apply to the field. Each should be a callable
that takes the parameters ``field_data, all_data`` and raises
``django.core.validators.ValidationError`` for errors. (See the
`validator docs`_.)
Django comes with quite a few validators. They're in ``django.core.validators``.
2008-07-21 16:38:54 +00:00
.. _validator docs: ../oldforms/#validators
2006-05-02 01:31:56 +00:00
Verbose field names
-------------------
Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
``OneToOneField``, takes an optional first positional argument -- a
verbose name. If the verbose name isn't given, Django will automatically create
it using the field's attribute name, converting underscores to spaces.
In this example, the verbose name is ``"Person's first name"``::
2007-08-05 05:14:46 +00:00
first_name = models.CharField("Person's first name", max_length=30)
2006-05-02 01:31:56 +00:00
In this example, the verbose name is ``"first name"``::
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=30)
2006-05-02 01:31:56 +00:00
``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
argument to be a model class, so use the ``verbose_name`` keyword argument::
poll = models.ForeignKey(Poll, verbose_name="the related poll")
sites = models.ManyToManyField(Site, verbose_name="list of sites")
place = models.OneToOneField(Place, verbose_name="related place")
Convention is not to capitalize the first letter of the ``verbose_name``.
Django will automatically capitalize the first letter where it needs to.
2005-08-26 18:29:11 +00:00
Relationships
-------------
Clearly, the power of relational databases lies in relating tables to each
2006-05-02 01:31:56 +00:00
other. Django offers ways to define the three most common types of database
2005-08-26 18:29:11 +00:00
relationships: Many-to-one, many-to-many and one-to-one.
Many-to-one relationships
~~~~~~~~~~~~~~~~~~~~~~~~~
To define a many-to-one relationship, use ``ForeignKey``. You use it just like
any other ``Field`` type: by including it as a class attribute of your model.
2007-08-07 02:33:11 +00:00
``ForeignKey`` requires a positional argument: the class to which the model is
2005-08-26 18:29:11 +00:00
related.
2006-05-04 04:59:45 +00:00
For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
``Manufacturer`` makes multiple cars but each ``Car`` only has one
``Manufacturer`` -- use the following definitions::
2005-08-26 18:29:11 +00:00
2006-05-04 04:59:45 +00:00
class Manufacturer(models.Model):
2005-08-26 18:29:11 +00:00
# ...
2006-05-04 04:59:45 +00:00
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
2005-08-26 18:29:11 +00:00
# ...
2005-07-17 04:20:57 +00:00
2005-08-26 18:29:11 +00:00
To create a recursive relationship -- an object that has a many-to-one
2006-05-02 01:31:56 +00:00
relationship with itself -- use ``models.ForeignKey('self')``.
If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself::
2006-05-04 04:59:45 +00:00
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
2006-05-02 01:31:56 +00:00
# ...
2006-05-04 04:59:45 +00:00
class Manufacturer(models.Model):
2006-05-02 01:31:56 +00:00
# ...
2005-07-21 03:46:16 +00:00
2008-02-26 21:18:34 +00:00
Note, however, that this only refers to models in the same models.py file -- you
cannot use a string to reference a model defined in another application or
imported from elsewhere.
2008-03-13 20:23:06 +00:00
**New in Django development version:** To refer to models defined in another
application, you must instead explicitly specify the application label. For
example, if the ``Manufacturer`` model above is defined in another application
called ``production``, you'd need to use::
2008-02-26 21:18:34 +00:00
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
2006-05-04 04:59:45 +00:00
Behind the scenes, Django appends ``"_id"`` to the field name to create its
database column name. In the above example, the database table for the ``Car``
model will have a ``manufacturer_id`` column. (You can change this explicitly
by specifying ``db_column``; see ``db_column`` below.) However, your code
2006-05-02 01:31:56 +00:00
should never have to deal with the database column name, unless you write
2006-05-04 04:59:45 +00:00
custom SQL. You'll always deal with the field names of your model object.
It's suggested, but not required, that the name of a ``ForeignKey`` field
(``manufacturer`` in the example above) be the name of the model, lowercase.
You can, of course, call the field whatever you want. For example::
class Car(models.Model):
company_that_makes_it = models.ForeignKey(Manufacturer)
# ...
2005-07-21 03:46:16 +00:00
2005-08-26 18:35:44 +00:00
See the `Many-to-one relationship model example`_ for a full example.
2005-07-17 04:20:57 +00:00
2007-08-05 04:42:26 +00:00
.. _Many-to-one relationship model example: ../models/many_to_one/
2005-08-26 18:29:11 +00:00
``ForeignKey`` fields take a number of extra arguments for defining how the
relationship should work. All are optional:
2005-07-17 04:20:57 +00:00
2005-07-15 00:54:49 +00:00
======================= ============================================================
2005-07-18 20:53:02 +00:00
Argument Description
2005-07-15 00:54:49 +00:00
======================= ============================================================
2005-07-13 01:25:57 +00:00
``limit_choices_to`` A dictionary of lookup arguments and values (see
2005-07-17 04:20:57 +00:00
the `Database API reference`_) that limit the
available admin choices for this object. Use this
2007-05-21 20:45:33 +00:00
with functions from the Python ``datetime`` module
2007-04-09 13:28:09 +00:00
to limit choices of objects by date. For example::
2005-07-17 04:20:57 +00:00
2007-04-09 13:28:09 +00:00
limit_choices_to = {'pub_date__lte': datetime.now}
2005-07-17 04:20:57 +00:00
2005-07-13 01:25:57 +00:00
only allows the choice of related objects with a
``pub_date`` before the current date/time to be
chosen.
2005-07-17 04:20:57 +00:00
2006-05-06 00:26:24 +00:00
Instead of a dictionary this can also be a ``Q`` object
(an object with a ``get_sql()`` method) for more complex
queries.
2005-07-13 01:25:57 +00:00
Not compatible with ``edit_inline``.
2005-07-17 04:20:57 +00:00
2005-07-13 01:25:57 +00:00
``related_name`` The name to use for the relation from the related
2006-05-04 04:59:45 +00:00
object back to this one. See the
`related objects documentation`_ for a full
explanation and example.
2005-07-17 04:20:57 +00:00
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
If using this in an `abstract base class`_, be
sure to read the `extra notes`_ in that section
about ``related_name``.
2005-07-15 00:42:28 +00:00
``to_field`` The field on the related object that the relation
2005-08-26 18:29:11 +00:00
is to. By default, Django uses the primary key of
the related object.
2005-07-15 00:54:49 +00:00
======================= ============================================================
2005-07-13 01:25:57 +00:00
2007-04-13 01:19:44 +00:00
.. _`Database API reference`: ../db-api/
.. _related objects documentation: ../db-api/#related-objects
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
.. _abstract base class: `Abstract base classes`_
.. _extra notes: `Be careful with related_name`_
2005-07-17 04:20:57 +00:00
2005-08-26 18:29:11 +00:00
Many-to-many relationships
~~~~~~~~~~~~~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2005-11-19 20:20:13 +00:00
To define a many-to-many relationship, use ``ManyToManyField``. You use it just
2005-08-26 18:29:11 +00:00
like any other ``Field`` type: by including it as a class attribute of your
model.
2005-07-17 04:20:57 +00:00
2007-08-07 02:33:11 +00:00
``ManyToManyField`` requires a positional argument: the class to which the
2005-08-26 18:29:11 +00:00
model is related.
2005-07-17 04:20:57 +00:00
2005-08-26 18:29:11 +00:00
For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
here's how you'd represent that::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Topping(models.Model):
2005-08-26 18:29:11 +00:00
# ...
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Pizza(models.Model):
2005-08-26 18:29:11 +00:00
# ...
2006-05-02 01:31:56 +00:00
toppings = models.ManyToManyField(Topping)
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
As with ``ForeignKey``, a relationship to self can be defined by using the
2006-05-04 04:59:45 +00:00
string ``'self'`` instead of the model name, and you can refer to as-yet
2006-08-18 02:48:34 +00:00
undefined models by using a string containing the model name. However, you
can only use strings to refer to models in the same models.py file -- you
cannot use a string to reference a model in a different application, or to
2006-08-17 00:02:51 +00:00
reference a model that has been imported from elsewhere.
2006-05-02 01:31:56 +00:00
2006-05-04 04:59:45 +00:00
It's suggested, but not required, that the name of a ``ManyToManyField``
(``toppings`` in the example above) be a plural describing the set of related
model objects.
2005-08-26 18:29:11 +00:00
Behind the scenes, Django creates an intermediary join table to represent the
many-to-many relationship.
It doesn't matter which model gets the ``ManyToManyField``, but you only need
it in one of the models -- not in both.
Generally, ``ManyToManyField`` instances should go in the object that's going
2006-05-04 04:59:45 +00:00
to be edited in the admin interface, if you're using Django's admin. In the
above example, ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a
``pizzas`` ``ManyToManyField`` ) because it's more natural to think about a
``Pizza`` having toppings than a topping being on multiple pizzas. The way it's
set up above, the ``Pizza`` admin form would let users select the toppings.
2005-07-17 04:20:57 +00:00
2005-08-26 18:35:44 +00:00
See the `Many-to-many relationship model example`_ for a full example.
2005-08-26 18:29:11 +00:00
2007-08-05 04:42:26 +00:00
.. _Many-to-many relationship model example: ../models/many_to_many/
2005-08-26 18:29:11 +00:00
``ManyToManyField`` objects take a number of extra arguments for defining how
the relationship should work. All are optional:
2005-07-17 04:20:57 +00:00
2005-07-15 20:37:03 +00:00
======================= ============================================================
2005-07-18 20:53:02 +00:00
Argument Description
2005-07-15 20:37:03 +00:00
======================= ============================================================
2006-05-04 04:59:45 +00:00
``related_name`` See the description under ``ForeignKey`` above.
2005-07-17 04:20:57 +00:00
2005-08-04 19:00:20 +00:00
``limit_choices_to`` See the description under ``ForeignKey`` above.
2005-10-30 14:35:44 +00:00
2006-05-02 01:31:56 +00:00
``symmetrical`` Only used in the definition of ManyToManyFields on self.
2008-02-15 11:38:53 +00:00
Consider the following model::
2006-05-02 01:31:56 +00:00
2008-02-15 11:38:53 +00:00
class Person(models.Model):
friends = models.ManyToManyField("self")
2006-05-02 01:31:56 +00:00
When Django processes this model, it identifies that it has
2006-05-04 04:59:45 +00:00
a ``ManyToManyField`` on itself, and as a result, it
doesn't add a ``person_set`` attribute to the ``Person``
class. Instead, the ``ManyToManyField`` is assumed to be
symmetrical -- that is, if I am your friend, then you are
my friend.
If you do not want symmetry in ``ManyToMany`` relationships
with ``self``, set ``symmetrical`` to ``False``. This will
force Django to add the descriptor for the reverse
relationship, allowing ``ManyToMany`` relationships to be
non-symmetrical.
2007-02-18 04:44:17 +00:00
``db_table`` The name of the table to create for storing the many-to-many
2007-01-25 13:47:55 +00:00
data. If this is not provided, Django will assume a default
name based upon the names of the two tables being joined.
2006-05-02 01:31:56 +00:00
2005-07-15 20:37:03 +00:00
======================= ============================================================
2008-07-29 12:41:08 +00:00
Extra fields on many-to-many relationships
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**New in Django development version**
When you're only dealing with simple many-to-many relationships such as
mixing and matching pizzas and toppings, a standard ``ManyToManyField``
is all you need. However, sometimes you may need to associate data with the
relationship between two models.
For example, consider the case of an application tracking the musical groups
which musicians belong to. There is a many-to-many relationship between a person
and the groups of which they are a member, so you could use a ManyToManyField
to represent this relationship. However, there is a lot of detail about the
membership that you might want to collect, such as the date at which the person
joined the group.
For these situations, Django allows you to specify the model that will be used
to govern the many-to-many relationship. You can then put extra fields on the
intermediate model. The intermediate model is associated with the
``ManyToManyField`` using the ``through`` argument to point to the model
that will act as an intermediary. For our musician example, the code would look
something like this::
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __unicode__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
When you set up the intermediary model, you explicitly specify foreign
keys to the models that are involved in the ManyToMany relation. This
explicit declaration defines how the two models are related.
There are a few restrictions on the intermediate model:
* Your intermediate model must contain one - and *only* one - foreign key
on the target model (this would be ``Person`` in our example). If you
have more than one foreign key, a validation error will be raised.
* Your intermediate model must contain one - and *only* one - foreign key
on the source model (this would be ``Group`` in our example). If you
have more than one foreign key, a validation error will be raised.
2008-08-01 04:38:55 +00:00
* The only exception to this is a model which has a many-to-many
relationship to itself, through an intermediary model. In this
case, two foreign keys to the same model are permitted, but they
will be treated as the two (different) sides of the many-to-many
relation.
* When defining a many-to-many relationship from a model to
itself, using an intermediary model, you *must* use
``symmetrical=False`` (see the documentation for
``ManyToManyField`` above).
2008-07-29 12:41:08 +00:00
Now that you have set up your ``ManyToManyField`` to use your intermediary
model (Membership, in this case), you're ready to start creating some
many-to-many relationships. You do this by creating instances of the
intermediate model::
>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
... date_joined=date(1962, 8, 16),
... invite_reason= "Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
[<Person: Ringo Starr>]
>>> ringo.group_set.all()
[<Group: The Beatles>]
>>> m2 = Membership.objects.create(person=paul, group=beatles,
... date_joined=date(1960, 8, 1),
... invite_reason= "Wanted to form a band.")
>>> beatles.members.all()
[<Person: Ringo Starr>, <Person: Paul McCartney>]
Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
or assignment (i.e., ``beatles.members = [...]``) to create relationships::
# THIS WILL NOT WORK
>>> beatles.members.add(john)
# NEITHER WILL THIS
>>> beatles.members.create(name="George Harrison")
# AND NEITHER WILL THIS
>>> beatles.members = [john, paul, ringo, george]
Why? You can't just create a relationship between a Person and a Group - you
need to specify all the detail for the relationship required by the
Membership table. The simple ``add``, ``create`` and assignment calls
don't provide a way to specify this extra detail. As a result, they are
disabled for many-to-many relationships that use an intermediate model.
The only way to create a many-to-many relationship with an intermediate table
is to create instances of the intermediate model.
The ``remove`` method is disabled for similar reasons. However, the
``clear()`` method can be used to remove all many-to-many relationships
for an instance::
# Beatles have broken up
>>> beatles.members.clear()
Once you have established the many-to-many relationships by creating instances
of your intermediate model, you can issue queries. Just as with normal
many-to-many relationships, you can query using the attributes of the
many-to-many-related model::
# Find all the groups with a member whose name starts with 'Paul'
>>> Groups.objects.filter(person__name__startswith='Paul')
[<Group: The Beatles>]
As you are using an intermediate table, you can also query on the attributes
of the intermediate model::
# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
... group__name='The Beatles',
... membership__date_joined__gt=date(1961,1,1))
[<Person: Ringo Starr]
2005-08-26 18:29:11 +00:00
One-to-one relationships
~~~~~~~~~~~~~~~~~~~~~~~~
2005-07-17 04:20:57 +00:00
2005-08-26 18:29:11 +00:00
To define a one-to-one relationship, use ``OneToOneField``. You use it just
like any other ``Field`` type: by including it as a class attribute of your
model.
2005-07-17 04:20:57 +00:00
2005-08-26 18:29:11 +00:00
This is most useful on the primary key of an object when that object "extends"
another object in some way.
2005-07-17 04:20:57 +00:00
2007-08-07 02:33:11 +00:00
``OneToOneField`` requires a positional argument: the class to which the
2005-08-26 18:29:11 +00:00
model is related.
2005-07-17 04:20:57 +00:00
2005-08-26 18:29:11 +00:00
For example, if you're building a database of "places", you would build pretty
standard stuff such as address, phone number, etc. in the database. Then, if you
wanted to build a database of restaurants on top of the places, instead of
repeating yourself and replicating those fields in the ``Restaurant`` model, you
could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
restaurant "is-a" place).
2005-07-15 20:37:03 +00:00
2006-05-02 01:31:56 +00:00
As with ``ForeignKey``, a relationship to self can be defined by using the
string ``"self"`` instead of the model name; references to as-yet undefined
models can be made by using a string containing the model name.
2005-07-17 04:20:57 +00:00
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
Finally, ``OneToOneField`` takes the following extra option:
======================= ============================================================
Argument Description
======================= ============================================================
``parent_link`` When ``True`` and used in a model inherited from
another model, indicates that this field should
be used as the link from the child back to the
parent. See `Model inheritance`_ for more
details.
**New in Django development version**
======================= ============================================================
**New in Django development version:** ``OneToOneField`` classes used to
automatically become the primary key on a model. This is no longer true,
although you can manually pass in the ``primary_key`` attribute if you like.
Thus, it's now possible to have multiple fields of type ``OneToOneField`` on a
single model.
2005-07-17 04:20:57 +00:00
2005-08-26 18:35:44 +00:00
See the `One-to-one relationship model example`_ for a full example.
2005-07-17 04:20:57 +00:00
2007-08-05 04:42:26 +00:00
.. _One-to-one relationship model example: ../models/one_to_one/
2005-07-17 04:20:57 +00:00
2007-07-20 06:28:56 +00:00
Custom field types
------------------
2008-03-14 00:07:01 +00:00
**New in Django development version**
2007-11-05 13:59:52 +00:00
If one of the existing model fields cannot be used to fit your purposes, or if
you wish to take advantage of some less common database column types, you can
create your own field class. Full coverage of creating your own fields is
provided in the `Custom Model Fields`_ documentation.
2007-07-20 21:24:30 +00:00
2007-11-05 13:59:52 +00:00
.. _Custom Model Fields: ../custom_model_fields/
2007-07-20 21:24:30 +00:00
2006-05-02 01:31:56 +00:00
Meta options
2005-08-26 18:29:11 +00:00
============
2005-08-15 16:15:26 +00:00
2006-05-02 01:31:56 +00:00
Give your model metadata by using an inner ``class Meta``, like so::
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Foo(models.Model):
2007-08-05 05:14:46 +00:00
bar = models.CharField(max_length=30)
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
class Meta:
# ...
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Model metadata is "anything that's not a field", such as ordering options, etc.
2005-07-17 04:20:57 +00:00
2006-05-02 01:31:56 +00:00
Here's a list of all possible ``Meta`` options. No options are required. Adding
``class Meta`` to a model is completely optional.
2005-07-17 04:20:57 +00:00
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
``abstract``
------------
**New in Django development version**
When set to ``True``, denotes this model as an abstract base class. See
`Abstract base classes`_ for more details. Defaults to ``False``.
2005-08-26 18:29:11 +00:00
``db_table``
2006-05-02 01:31:56 +00:00
------------
2005-07-17 04:20:57 +00:00
2006-05-04 04:59:45 +00:00
The name of the database table to use for the model::
2005-07-17 04:20:57 +00:00
2006-05-04 04:59:45 +00:00
db_table = 'music_album'
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
If this isn't given, Django will use ``app_label + '_' + model_class_name``.
2006-05-04 04:59:45 +00:00
See "Table names" below for more.
2005-11-14 01:44:35 +00:00
2006-05-02 01:31:56 +00:00
If your database table name is an SQL reserved word, or contains characters
that aren't allowed in Python variable names -- notably, the hyphen --
that's OK. Django quotes column and table names behind the scenes.
2005-08-26 18:29:11 +00:00
2007-06-23 14:16:00 +00:00
``db_tablespace``
-----------------
2007-06-30 20:58:36 +00:00
**New in Django development version**
2007-06-23 14:16:00 +00:00
The name of the database tablespace to use for the model. If the backend
doesn't support tablespaces, this option is ignored.
2005-08-26 18:29:11 +00:00
``get_latest_by``
2006-05-02 01:31:56 +00:00
-----------------
2005-08-26 18:29:11 +00:00
2006-05-04 04:59:45 +00:00
The name of a ``DateField`` or ``DateTimeField`` in the model. This specifies
the default field to use in your model ``Manager``'s ``latest()`` method.
Example::
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
get_latest_by = "order_date"
2005-08-26 18:29:11 +00:00
2006-05-04 04:59:45 +00:00
See the `docs for latest()`_ for more.
2005-08-26 18:29:11 +00:00
2007-04-13 01:19:44 +00:00
.. _docs for latest(): ../db-api/#latest-field-name-none
2005-08-26 18:29:11 +00:00
``order_with_respect_to``
2006-05-02 01:31:56 +00:00
-------------------------
Marks this object as "orderable" with respect to the given field. This is
almost always used with related objects to allow them to be ordered with
2006-05-04 04:59:45 +00:00
respect to a parent object. For example, if an ``Answer`` relates to a
``Question`` object, and a question has more than one answer, and the order
of answers matters, you'd do this::
2005-08-26 18:29:11 +00:00
2006-05-04 04:59:45 +00:00
class Answer(models.Model):
question = models.ForeignKey(Question)
# ...
2005-08-26 18:29:11 +00:00
2006-05-04 04:59:45 +00:00
class Meta:
order_with_respect_to = 'question'
2005-08-26 18:29:11 +00:00
``ordering``
2006-05-02 01:31:56 +00:00
------------
The default ordering for the object, for use when obtaining lists of objects::
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
ordering = ['-order_date']
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
This is a tuple or list of strings. Each string is a field name with an
optional "-" prefix, which indicates descending order. Fields without a
leading "-" will be ordered ascending. Use the string "?" to order randomly.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
For example, to order by a ``pub_date`` field ascending, use this::
2006-04-13 01:45:15 +00:00
2006-05-02 01:31:56 +00:00
ordering = ['pub_date']
2006-04-13 01:45:15 +00:00
2006-05-02 01:31:56 +00:00
To order by ``pub_date`` descending, use this::
2006-04-13 01:45:15 +00:00
2006-05-02 01:31:56 +00:00
ordering = ['-pub_date']
2006-04-13 01:45:15 +00:00
2006-05-02 01:31:56 +00:00
To order by ``pub_date`` descending, then by ``author`` ascending, use this::
2006-04-13 01:45:15 +00:00
2006-05-02 01:31:56 +00:00
ordering = ['-pub_date', 'author']
2006-04-13 01:45:15 +00:00
2006-05-02 01:31:56 +00:00
See `Specifying ordering`_ for more examples.
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Note that, regardless of how many fields are in ``ordering``, the admin
site uses only the first field.
2006-04-13 01:46:08 +00:00
2007-08-05 04:42:26 +00:00
.. _Specifying ordering: ../models/ordering/
2005-08-26 18:29:11 +00:00
``permissions``
2006-05-02 01:31:56 +00:00
---------------
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Extra permissions to enter into the permissions table when creating this
object. Add, delete and change permissions are automatically created for
each object that has ``admin`` set. This example specifies an extra
permission, ``can_deliver_pizzas``::
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
This is a list or tuple of 2-tuples in the format
``(permission_code, human_readable_permission_name)``.
2005-08-26 18:29:11 +00:00
``unique_together``
2006-05-02 01:31:56 +00:00
-------------------
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
Sets of field names that, taken together, must be unique::
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
unique_together = (("driver", "restaurant"),)
This is a list of lists of fields that must be unique when considered
together. It's used in the Django admin and is enforced at the database
level (i.e., the appropriate ``UNIQUE`` statements are included in the
``CREATE TABLE`` statement).
2005-08-26 18:29:11 +00:00
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
All the fields specified in ``unique_together`` must be part of the current
model. If you are using `model inheritance`_, you cannot refer to fields from
any parent classes in ``unique_together``.
2007-09-14 20:36:53 +00:00
**New in Django development version**
For convenience, unique_together can be a single list when dealing
with a single set of fields::
2008-07-29 12:41:08 +00:00
unique_together = ("driver", "restaurant")
2007-09-14 20:36:53 +00:00
2005-08-26 18:29:11 +00:00
``verbose_name``
2006-05-02 01:31:56 +00:00
----------------
A human-readable name for the object, singular::
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
verbose_name = "pizza"
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
If this isn't given, Django will use a munged version of the class name:
``CamelCase`` becomes ``camel case``.
2005-08-26 18:29:11 +00:00
``verbose_name_plural``
2006-05-02 01:31:56 +00:00
-----------------------
The plural name for the object::
verbose_name_plural = "stories"
2005-08-26 18:29:11 +00:00
2006-05-02 01:31:56 +00:00
If this isn't given, Django will use ``verbose_name + "s"``.
2006-05-04 04:59:45 +00:00
Table names
===========
2006-05-02 01:31:56 +00:00
2006-05-04 04:59:45 +00:00
To save you time, Django automatically derives the name of the database table
from the name of your model class and the app that contains it. A model's
database table name is constructed by joining the model's "app label" -- the
name you used in ``manage.py startapp`` -- to the model's class name, with an
underscore between them.
2006-05-02 01:31:56 +00:00
2006-05-04 04:59:45 +00:00
For example, if you have an app ``bookstore`` (as created by
``manage.py startapp bookstore``), a model defined as ``class Book`` will have
a database table named ``bookstore_book``.
2006-05-02 01:31:56 +00:00
2006-05-04 04:59:45 +00:00
To override the database table name, use the ``db_table`` parameter in
``class Meta``.
2006-05-02 01:31:56 +00:00
Automatic primary key fields
============================
2005-08-26 18:29:11 +00:00
2006-05-04 04:59:45 +00:00
By default, Django gives each model the following field::
id = models.AutoField(primary_key=True)
This is an auto-incrementing primary key.
If you'd like to specify a custom primary key, just specify ``primary_key=True``
on one of your fields. If Django sees you've explicitly set ``primary_key``, it
won't add the automatic ``id`` column.
Each model requires exactly one field to have ``primary_key=True``.
2005-07-13 01:25:57 +00:00
2007-09-16 01:57:25 +00:00
The ``pk`` property
-------------------
**New in Django development version**
Regardless of whether you define a primary key field yourself, or let Django
supply one for you, each model will have a property called ``pk``. It behaves
like a normal attribute on the model, but is actually an alias for whichever
attribute is the primary key field for the model. You can read and set this
value, just as you would for any other attribute, and it will update the
correct field in the model.
2006-05-02 01:31:56 +00:00
Managers
========
2006-05-05 01:56:29 +00:00
A ``Manager`` is the interface through which database query operations are
provided to Django models. At least one ``Manager`` exists for every model in
a Django application.
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
The way ``Manager`` classes work is documented in the `Retrieving objects`_
section of the database API docs, but this section specifically touches on
model options that customize ``Manager`` behavior.
2007-04-13 01:19:44 +00:00
.. _Retrieving objects: ../db-api/#retrieving-objects
2006-05-09 15:21:28 +00:00
2006-05-05 01:56:29 +00:00
Manager names
-------------
By default, Django adds a ``Manager`` with the name ``objects`` to every Django
model class. However, if you want to use ``objects`` as a field name, or if you
want to use a name other than ``objects`` for the ``Manager``, you can rename
it on a per-model basis. To rename the ``Manager`` for a given class, define a
class attribute of type ``models.Manager()`` on that model. For example::
2006-05-02 01:31:56 +00:00
from django.db import models
class Person(models.Model):
#...
people = models.Manager()
2006-05-05 01:56:29 +00:00
Using this example model, ``Person.objects`` will generate an
``AttributeError`` exception, but ``Person.people.all()`` will provide a list
of all ``Person`` objects.
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
Custom Managers
---------------
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
You can use a custom ``Manager`` in a particular model by extending the base
``Manager`` class and instantiating your custom ``Manager`` in your model.
There are two reasons you might want to customize a ``Manager``: to add extra
``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
returns.
Adding extra Manager methods
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adding extra ``Manager`` methods is the preferred way to add "table-level"
functionality to your models. (For "row-level" functionality -- i.e., functions
2007-11-29 18:15:38 +00:00
that act on a single instance of a model object -- use `Model methods`_, not
2006-05-05 01:56:29 +00:00
custom ``Manager`` methods.)
A custom ``Manager`` method can return anything you want. It doesn't have to
return a ``QuerySet``.
For example, this custom ``Manager`` offers a method ``with_counts()``, which
returns a list of all ``OpinionPoll`` objects, each with an extra
``num_responses`` attribute that is the result of an aggregate query::
class PollManager(models.Manager):
def with_counts(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT p.id, p.question, p.poll_date, COUNT(*)
FROM polls_opinionpoll p, polls_response r
WHERE p.id = r.poll_id
GROUP BY 1, 2, 3
ORDER BY 3 DESC""")
result_list = []
for row in cursor.fetchall():
p = self.model(id=row[0], question=row[1], poll_date=row[2])
p.num_responses = row[3]
result_list.append(p)
return result_list
class OpinionPoll(models.Model):
2007-08-05 05:14:46 +00:00
question = models.CharField(max_length=200)
2006-05-05 01:56:29 +00:00
poll_date = models.DateField()
objects = PollManager()
class Response(models.Model):
poll = models.ForeignKey(Poll)
2007-08-05 05:14:46 +00:00
person_name = models.CharField(max_length=50)
2006-05-05 01:56:29 +00:00
response = models.TextField()
With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return
that list of ``OpinionPoll`` objects with ``num_responses`` attributes.
Another thing to note about this example is that ``Manager`` methods can
access ``self.model`` to get the model class to which they're attached.
Modifying initial Manager QuerySets
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
example, using this model::
class Book(models.Model):
2007-08-05 05:14:46 +00:00
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
2006-05-05 01:56:29 +00:00
...the statement ``Book.objects.all()`` will return all books in the database.
2006-05-09 15:21:28 +00:00
You can override a ``Manager``\'s base ``QuerySet`` by overriding the
2006-05-05 01:56:29 +00:00
``Manager.get_query_set()`` method. ``get_query_set()`` should return a
``QuerySet`` with the properties you require.
2006-05-09 15:21:28 +00:00
For example, the following model has *two* ``Manager``\s -- one that returns
2006-05-05 01:56:29 +00:00
all objects, and one that returns only the books by Roald Dahl::
# First, define the Manager subclass.
class DahlBookManager(models.Manager):
def get_query_set(self):
2006-05-09 21:32:56 +00:00
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
# Then hook it into the Book model explicitly.
class Book(models.Model):
2007-08-05 05:14:46 +00:00
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
objects = models.Manager() # The default manager.
dahl_objects = DahlBookManager() # The Dahl-specific manager.
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
With this sample model, ``Book.objects.all()`` will return all books in the
database, but ``Book.dahl_objects.all()`` will only return the ones written by
Roald Dahl.
Of course, because ``get_query_set()`` returns a ``QuerySet`` object, you can
use ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it.
So these statements are all legal::
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
Book.dahl_objects.all()
Book.dahl_objects.filter(title='Matilda')
Book.dahl_objects.count()
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
This example also pointed out another interesting technique: using multiple
managers on the same model. You can attach as many ``Manager()`` instances to
a model as you'd like. This is an easy way to define common "filters" for your
models.
For example::
2006-05-02 01:31:56 +00:00
class MaleManager(models.Manager):
def get_query_set(self):
2006-05-09 21:32:56 +00:00
return super(MaleManager, self).get_query_set().filter(sex='M')
2006-05-02 01:31:56 +00:00
class FemaleManager(models.Manager):
def get_query_set(self):
2006-05-09 21:32:56 +00:00
return super(FemaleManager, self).get_query_set().filter(sex='F')
2006-05-02 01:31:56 +00:00
class Person(models.Model):
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
2006-05-02 01:31:56 +00:00
people = models.Manager()
men = MaleManager()
women = FemaleManager()
2006-05-05 01:56:29 +00:00
This example allows you to request ``Person.men.all()``, ``Person.women.all()``,
2006-05-02 01:31:56 +00:00
and ``Person.people.all()``, yielding predictable results.
2008-03-18 19:55:21 +00:00
If you use custom ``Manager`` objects, take note that the first
``Manager`` Django encounters (in the order in which they're defined
in the model) has a special status. Django interprets this first
``Manager`` defined in a class as the "default" ``Manager``, and
several parts of Django (though not the admin application) will use
that ``Manager`` exclusively for that model. As a result, it's often a
good idea to be careful in your choice of default manager, in order to
avoid a situation where overriding of ``get_query_set()`` results in
an inability to retrieve objects you'd like to work with.
2006-05-02 01:31:56 +00:00
2005-07-15 20:37:03 +00:00
Model methods
=============
2006-05-05 01:56:29 +00:00
Define custom methods on a model to add custom "row-level" functionality to
your objects. Whereas ``Manager`` methods are intended to do "table-wide"
things, model methods should act on a particular model instance.
2005-07-15 20:37:03 +00:00
2006-05-05 01:56:29 +00:00
This is a valuable technique for keeping business logic in one place -- the
model.
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
For example, this model has a few custom methods::
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
class Person(models.Model):
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
2006-05-05 01:56:29 +00:00
birth_date = models.DateField()
2007-08-05 05:14:46 +00:00
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
2006-05-05 01:56:29 +00:00
state = models.USStateField() # Yes, this is America-centric...
2005-07-15 20:37:03 +00:00
2006-05-05 18:31:16 +00:00
def baby_boomer_status(self):
"Returns the person's baby-boomer status."
import datetime
if datetime.date(1945, 8, 1) <= self.birth_date <= datetime.date(1964, 12, 31):
return "Baby boomer"
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
return "Post-boomer"
def is_midwestern(self):
"Returns True if this person is from the Midwest."
return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
def _get_full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)
2005-07-15 20:37:03 +00:00
2006-05-05 01:56:29 +00:00
The last method in this example is a *property*. `Read more about properties`_.
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
.. _Read more about properties: http://www.python.org/download/releases/2.2/descrintro/#property
2005-08-26 18:29:11 +00:00
2006-05-05 01:56:29 +00:00
A few object methods have special meaning:
2005-08-26 18:29:11 +00:00
2006-05-05 01:56:29 +00:00
``__str__``
-----------
2005-08-26 18:29:11 +00:00
2006-05-05 01:56:29 +00:00
``__str__()`` is a Python "magic method" that defines what should be returned
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 12:11:04 +00:00
if you call ``str()`` on the object. Django uses ``str(obj)`` (or the related
function, ``unicode(obj)`` -- see below) in a number of places, most notably
as the value displayed to render an object in the Django admin site and as the
value inserted into a template when it displays an object. Thus, you should
always return a nice, human-readable string for the object's ``__str__``.
Although this isn't required, it's strongly encouraged (see the description of
2007-09-08 19:30:16 +00:00
``__unicode__``, below, before putting ``__str__`` methods everywhere).
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
For example::
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
class Person(models.Model):
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
2005-08-26 18:29:11 +00:00
2006-05-05 01:56:29 +00:00
def __str__(self):
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 12:11:04 +00:00
# Note use of django.utils.encoding.smart_str() here because
# first_name and last_name will be unicode strings.
return smart_str('%s %s' % (self.first_name, self.last_name))
``__unicode__``
---------------
The ``__unicode__()`` method is called whenever you call ``unicode()`` on an
object. Since Django's database backends will return Unicode strings in your
model's attributes, you would normally want to write a ``__unicode__()``
method for your model. The example in the previous section could be written
more simply as::
class Person(models.Model):
2007-08-05 05:14:46 +00:00
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 12:11:04 +00:00
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
If you define a ``__unicode__()`` method on your model and not a ``__str__()``
method, Django will automatically provide you with a ``__str__()`` that calls
2008-02-15 11:38:53 +00:00
``__unicode__()`` and then converts the result correctly to a UTF-8 encoded
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 12:11:04 +00:00
string object. This is recommended development practice: define only
``__unicode__()`` and let Django take care of the conversion to string objects
when required.
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
``get_absolute_url``
2005-07-15 20:37:03 +00:00
--------------------
2006-05-05 01:56:29 +00:00
Define a ``get_absolute_url()`` method to tell Django how to calculate the
URL for an object. For example::
2006-05-02 01:31:56 +00:00
2006-05-05 01:56:29 +00:00
def get_absolute_url(self):
return "/people/%i/" % self.id
2005-07-17 04:20:57 +00:00
2006-05-05 01:56:29 +00:00
Django uses this in its admin interface. If an object defines
``get_absolute_url()``, the object-editing page will have a "View on site"
link that will jump you directly to the object's public view, according to
``get_absolute_url()``.
2005-07-15 20:37:03 +00:00
2007-08-04 03:19:14 +00:00
Also, a couple of other bits of Django, such as the `syndication feed framework`_,
2006-05-05 01:56:29 +00:00
use ``get_absolute_url()`` as a convenience to reward people who've defined the
method.
2005-07-17 04:20:57 +00:00
2007-08-07 02:33:11 +00:00
.. _syndication feed framework: ../syndication_feeds/
2007-08-04 03:19:14 +00:00
2006-05-05 01:56:29 +00:00
It's good practice to use ``get_absolute_url()`` in templates, instead of
hard-coding your objects' URLs. For example, this template code is bad::
2005-07-15 20:37:03 +00:00
2006-05-05 01:56:29 +00:00
<a href="/people/{{ object.id }}/">{{ object.name }}</a>
2006-05-04 04:59:45 +00:00
2006-05-05 01:56:29 +00:00
But this template code is good::
2005-07-15 20:37:03 +00:00
2006-05-05 01:56:29 +00:00
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
2005-07-17 04:20:57 +00:00
2007-05-15 18:03:00 +00:00
.. note::
2007-05-19 18:35:42 +00:00
The string you return from ``get_absolute_url()`` must contain only ASCII
2007-05-18 16:40:27 +00:00
characters (required by the URI spec, `RFC 2396`_) that have been
2007-05-15 18:03:00 +00:00
URL-encoded, if necessary. Code and templates using ``get_absolute_url()``
should be able to use the result directly without needing to do any
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 12:11:04 +00:00
further processing. You may wish to use the
``django.utils.encoding.iri_to_uri()`` function to help with this if you
are using unicode strings a lot.
2007-05-15 18:03:00 +00:00
.. _RFC 2396: http://www.ietf.org/rfc/rfc2396.txt
2007-02-18 04:44:17 +00:00
The ``permalink`` decorator
~~~~~~~~~~~~~~~~~~~~~~~~~~~
2007-02-17 05:51:45 +00:00
The problem with the way we wrote ``get_absolute_url()`` above is that it
slightly violates the DRY principle: the URL for this object is defined both
in the URLConf file and in the model.
2007-02-18 04:44:17 +00:00
You can further decouple your models from the URLconf using the ``permalink``
2007-03-31 11:35:06 +00:00
decorator. This decorator is passed the view function, a list of positional
2007-04-01 05:22:14 +00:00
parameters and (optionally) a dictionary of named parameters. Django then
2007-03-31 11:35:06 +00:00
works out the correct full URL path using the URLconf, substituting the
parameters you have given into the URL. For example, if your URLconf
contained a line such as::
2007-07-10 02:34:42 +00:00
(r'^people/(\d+)/$', 'people.views.details'),
2007-03-31 11:35:06 +00:00
...your model could have a ``get_absolute_url`` method that looked like this::
2007-02-17 05:51:45 +00:00
from django.db.models import permalink
def get_absolute_url(self):
2007-03-31 11:35:06 +00:00
return ('people.views.details', [str(self.id)])
get_absolute_url = permalink(get_absolute_url)
2007-04-01 05:22:14 +00:00
Similarly, if you had a URLconf entry that looked like::
2007-03-31 11:35:06 +00:00
2007-04-01 05:22:14 +00:00
(r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)
2007-03-31 11:35:06 +00:00
...you could reference this using ``permalink()`` as follows::
def get_absolute_url(self):
return ('archive_view', (), {
'year': self.created.year,
'month': self.created.month,
'day': self.created.day})
2007-02-17 05:51:45 +00:00
get_absolute_url = permalink(get_absolute_url)
2007-08-07 02:33:11 +00:00
Notice that we specify an empty sequence for the second parameter in this case,
because we only want to pass keyword parameters, not positional ones.
2007-03-31 11:35:06 +00:00
2007-02-18 04:44:17 +00:00
In this way, you're tying the model's absolute URL to the view that is used
to display it, without repeating the URL information anywhere. You can still
use the ``get_absolute_url`` method in templates, as before.
2005-08-26 19:02:07 +00:00
2008-06-17 13:56:10 +00:00
In some cases, such as the use of generic views or the re-use of
custom views for multiple models, specifying the view function may
confuse the reverse URL matcher (because multiple patterns point to
the same view).
For that problem, Django has **named URL patterns**. Using a named
2008-06-17 15:46:59 +00:00
URL pattern, it's possible to give a name to a pattern, and then
reference the name rather than the view function. A named URL
2008-06-17 13:56:10 +00:00
pattern is defined by replacing the pattern tuple by a call to
the ``url`` function)::
from django.conf.urls.defaults import *
url(r'^people/(\d+)/$',
'django.views.generic.list_detail.object_detail',
name='people_view'),
2008-06-26 03:59:15 +00:00
...and then using that name to perform the reverse URL resolution instead
2008-06-17 13:56:10 +00:00
of the view name::
from django.db.models import permalink
def get_absolute_url(self):
return ('people_view', [str(self.id)])
get_absolute_url = permalink(get_absolute_url)
2008-06-26 03:59:15 +00:00
More details on named URL patterns are in the `URL dispatch documentation`_.
2008-06-17 13:56:10 +00:00
2008-06-17 15:46:59 +00:00
.. _URL dispatch documentation: ../url_dispatch/#naming-url-patterns
2008-06-17 13:56:10 +00:00
2005-11-20 17:33:40 +00:00
Executing custom SQL
--------------------
Feel free to write custom SQL statements in custom model methods and
2006-05-05 01:56:29 +00:00
module-level methods. The object ``django.db.connection`` represents the
current database connection. To use it, call ``connection.cursor()`` to get a
cursor object. Then, call ``cursor.execute(sql, [params])`` to execute the SQL
and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the resulting
rows. Example::
2005-11-20 17:33:40 +00:00
def my_custom_sql(self):
2006-05-02 01:31:56 +00:00
from django.db import connection
cursor = connection.cursor()
2005-11-20 17:33:40 +00:00
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
2007-06-07 18:12:12 +00:00
``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_
(except when it comes to `transaction handling`_). If you're not familiar with
the Python DB-API, note that the SQL statement in ``cursor.execute()`` uses
placeholders, ``"%s"``, rather than adding parameters directly within the SQL.
If you use this technique, the underlying database library will automatically
add quotes and escaping to your parameter(s) as necessary. (Also note that
Django expects the ``"%s"`` placeholder, *not* the ``"?"`` placeholder, which is
used by the SQLite Python bindings. This is for the sake of consistency and
sanity.)
2005-11-20 17:33:40 +00:00
2006-03-22 23:06:22 +00:00
A final note: If all you want to do is a custom ``WHERE`` clause, you can just
2007-06-20 19:38:19 +00:00
use the ``where``, ``tables`` and ``params`` arguments to the standard lookup
2006-03-22 23:06:22 +00:00
API. See `Other lookup options`_.
2005-11-20 17:33:40 +00:00
.. _Python DB-API: http://www.python.org/peps/pep-0249.html
2007-06-20 19:39:24 +00:00
.. _Other lookup options: ../db-api/#extra-select-none-where-none-params-none-tables-none
2007-06-07 18:12:12 +00:00
.. _transaction handling: ../transactions/
2005-11-20 17:33:40 +00:00
2006-05-22 03:01:02 +00:00
Overriding default model methods
--------------------------------
As explained in the `database API docs`_, each model gets a few methods
automatically -- most notably, ``save()`` and ``delete()``. You can override
these methods to alter behavior.
A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example::
class Blog(models.Model):
2007-08-05 05:14:46 +00:00
name = models.CharField(max_length=100)
2006-05-22 03:01:02 +00:00
tagline = models.TextField()
2006-06-14 03:34:52 +00:00
def save(self):
do_something()
super(Blog, self).save() # Call the "real" save() method.
do_something_else()
2006-05-22 03:01:02 +00:00
You can also prevent saving::
class Blog(models.Model):
2007-08-05 05:14:46 +00:00
name = models.CharField(max_length=100)
2006-05-22 03:01:02 +00:00
tagline = models.TextField()
2006-06-14 03:34:52 +00:00
def save(self):
if self.name == "Yoko Ono's blog":
return # Yoko shall never have her own blog!
else:
super(Blog, self).save() # Call the "real" save() method.
2006-05-22 03:01:02 +00:00
2007-04-13 01:19:44 +00:00
.. _database API docs: ../db-api/
2006-05-22 03:01:02 +00:00
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
Model inheritance
=================
**New in Django development version**
Model inheritance in Django works almost identically to the way normal class
inheritance works in Python. The only decision you have to make is whether you
want the parent models to be models in their own right (with their own
database tables), or if the parents are just holders of common information
that will only be visible through the child models.
Often, you will just want to use the parent class to hold information that you
don't want to have to type out for each child model. This class isn't going to
ever be used in isolation, so `abstract base classes`_ are what you're after. However, if you're subclassing an existing model (perhaps something from another application entirely), or want each model to have its own database table, `multi-table inheritance`_ is the way to go.
Abstract base classes
---------------------
Abstract base classes are useful when you want to put some common information
into a number of other models. You write your base class and put
``abstract=True`` in the ``Meta`` class. This model will then not be used to
create any database table. Instead, when it is used as a base class for other
models, its fields will be added to those of the child class. It is an error
to have fields in the abstract base class with the same name as those in the
child (and Django will raise an exception).
An example::
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract = True
class Student(CommonInfo):
home_group = models.CharField(max_length=5)
The ``Student`` model will have three fields: ``name``, ``age`` and
``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
model, since it is an abstract base class. It does not generate a database
table or have a manager or anything like that.
For many uses, this type of model inheritance will be exactly what you want.
It provides a way to factor out common information at the Python level, whilst
still only creating one database table per child model at the database level.
``Meta`` inheritance
~~~~~~~~~~~~~~~~~~~~
When an abstract base class is created, Django makes any ``Meta`` inner class
you declared on the base class available as an attribute. If a child class
2008-06-30 06:42:50 +00:00
does not declare its own ``Meta`` class, it will inherit the parent's
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
``Meta``. If the child wants to extend the parent's ``Meta`` class, it can
subclass it. For example::
class CommonInfo(models.Model):
...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
Django does make one adjustment to the ``Meta`` class of an abstract base
class: before installing the ``Meta`` attribute, it sets ``abstract=False``.
This means that children of abstract base classes don't automatically become
abstract classes themselves. Of course, you can make an abstract base class
that inherits from another abstract base class. You just need to remember to
explicitly set ``abstract=True`` each time.
Some attributes won't make sense to include in the ``Meta`` class of an
abstract base class. For example, including ``db_table`` would mean that all
the child classes (the ones that don't specify their own ``Meta``) would use
the same database table, which is almost certainly not what you want.
Be careful with ``related_name``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you are using the ``related_name`` attribute on a ``ForeignKey`` or
``ManyToManyField``, you must always specify a *unique* reverse name for the
field. This would normally cause a problem in abstract base classes, since the
fields on this class are included into each of the child classes, with exactly
the same values for the attributes (including ``related_name``) each time.
To work around this problem, when you are using ``related_name`` in an
abstract base class (only), part of the name should be the string
``'%(class)s'``. This is replaced by the lower-cased name of the child class
that the field is used in. Since each class has a different name, each related
name will end up being different. For example::
class Base(models.Model):
m2m = models.ManyToMany(OtherModel, related_name="%(class)s_related")
class Meta:
abstract = True
class ChildA(Base):
pass
class ChildB(Base):
pass
The reverse name of the ``ChildA.m2m`` field will be ``childa_related``,
whilst the reverse name of the ``ChildB.m2m`` field will be
``childb_related``. It is up to you how you use the ``'%(class)s'`` portion to
construct your related name, but if you forget to use it, Django will raise
errors when you validate your models (or run ``syncdb``).
If you don't specify a ``related_name`` attribute for a field in an abstract
base class, the default reverse name will be the name of the child class
followed by ``'_set'``, just as it normally would be if you'd declared the field directly on the child class. For example, in the above code, if the ``related_name`` attribute was omitted, the reverse name for the ``m2m`` field would be ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB`` field.
Multi-table inheritance
-----------------------
The second type of model inheritance supported by Django is when each model in
the hierarchy is a model all by itself. Each model corresponds to its own
2008-04-27 11:55:47 +00:00
database table and can be queried and created individually. The inheritance
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
relationship introduces links between the child model and each of its parents
(via an automatically created ``OneToOneField``). For example::
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
All of the fields of ``Place`` will also be available in ``Restaurant``,
although the data will reside in a different database table. So these are both
possible::
>>> Place.objects.filter(name="Bob's Cafe")
>>> Restaurant.objects.filter(name="Bob's Cafe")
If you have a ``Place`` that is also a ``Restaurant``, you can get from the
``Place`` object to the ``Restaurant`` object by using the lower-case version
of the model name::
>>> p = Place.objects.filter(name="Bob's Cafe")
# If Bob's Cafe is a Restaurant object, this will give the child class:
>>> p.restaurant
<Restaurant: ...>
However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
created directly as a ``Place`` object or was the parent of some other class),
referring to ``p.restaurant`` would give an error.
``Meta`` and multi-table inheritance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the multi-table inheritance situation, it doesn't make sense for a child
class to inherit from its parent's ``Meta`` class. All the ``Meta`` options
have already been applied to the parent class and applying them again would
normally only lead to contradictory behaviour (this is in contrast with the
abstract base class case, where the base class doesn't exist in its own
right).
So a child model does not have access to its parent's ``Meta`` class. However,
there are a few limited cases where the child inherits behaviour from the
parent: if the child does not specify an ``ordering`` attribute or a
``get_latest_by`` attribute, it will inherit these from its parent.
If the parent has an ordering and you don't want the child to have any natural
2008-04-27 11:55:47 +00:00
ordering, you can explicitly set it to be empty::
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 02:50:16 +00:00
class ChildModel(ParentModel):
...
class Meta:
# Remove parent's ordering effect
ordering = []
Inheritance and reverse relations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because multi-table inheritance uses an implicit ``OneToOneField`` to link the
child and the parent, it's possible to move from the parent down to the child,
as in the above example. However, this uses up the name that is the default
``related_name`` value for ``ForeignKey`` and ``ManyToManyField`` relations.
If you are putting those type of relations on a subclass of another model, you
**must** specify the ``related_name`` attribute on each such field. If you
forget, Django will raise an error when you run ``manage.py validate`` or try
to syncdb.
For example, using the above ``Place`` class again, let's create another
subclass with a ``ManyToManyField``::
class Supplier(Place):
# Must specify related_name on all relations.
customers = models.ManyToManyField(Restaurant,
related_name='provider')
For more information about reverse relations, refer to the `Database API
reference`_ . For now, just remember to run ``manage.py validate`` when
you're writing your models and pay attention to the error messages.
Specifying the parent link field
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As mentioned, Django will automatically create a ``OneToOneField`` linking
your child class back any non-abstract parent models. If you want to control
the name of the attribute linking back to the parent, you can create your own
link field and pass it ``parent_link=True``. For example, to explicitly
specify the field that will link ``Supplier`` to ``Place`` in the above
example, you could write::
class Supplier(Place):
parent = models.OneToOneField(Place, parent_link=True)
...
Multiple inheritance
--------------------
Just as with Python's subclassing, it's possible for a Django model to inherit
from multiple parent models. Keep in mind that normal Python name resolution
rules apply. The first base class that a particular name appears in (e.g.
``Meta``) will be the one that is used. We stop searching once we find the
name once. This means that if multiple parents contain a ``Meta`` class, only
the first one is going to be used. All others will be ignored.
Generally, you won't need to inherit from multiple parents. The main use-case
where this is useful is for ''mix-in'' classes: adding a particular extra
field or method to every class that inherits the mix-in. Try to keep your
inheritance hierarchies as simple and straightforward as possible so that you
won't have to struggle to work out where a particular piece of information is
coming from.
2006-05-05 01:56:29 +00:00
Models across files
===================
It's perfectly OK to relate a model to one from another app. To do this, just
import the related model at the top of the model that holds your model. Then,
just refer to the other model class wherever needed. For example::
from mysite.geography.models import ZipCode
class Restaurant(models.Model):
# ...
zip_code = models.ForeignKey(ZipCode)
2005-08-26 19:02:07 +00:00
Using models
============
2006-05-05 01:56:29 +00:00
Once you have created your models, the final step is to tell Django you're
going to *use* those models.
Do this by editing your settings file and changing the ``INSTALLED_APPS``
setting to add the name of the module that contains your ``models.py``.
2005-08-26 19:02:07 +00:00
2006-05-05 01:56:29 +00:00
For example, if the models for your application live in the module
``mysite.myapp.models`` (the package structure that is created for an
application by the ``manage.py startapp`` script), ``INSTALLED_APPS`` should
read, in part::
2005-08-26 19:02:07 +00:00
2006-05-02 01:31:56 +00:00
INSTALLED_APPS = (
#...
2006-05-05 01:56:29 +00:00
'mysite.myapp',
2006-05-02 01:31:56 +00:00
#...
)
2006-05-19 03:37:50 +00:00
2006-05-19 05:07:33 +00:00
Providing initial SQL data
==========================
Django provides a hook for passing the database arbitrary SQL that's executed
just after the CREATE TABLE statements. Use this hook, for example, if you want
to populate default records, or create SQL functions, automatically.
The hook is simple: Django just looks for a file called
``<appname>/sql/<modelname>.sql``, where ``<appname>`` is your app directory and
``<modelname>`` is the model's name in lowercase.
In the ``Person`` example model at the top of this document, assuming it lives
in an app called ``myapp``, you could add arbitrary SQL to the file
``myapp/sql/person.sql``. Here's an example of what the file might contain::
INSERT INTO myapp_person (first_name, last_name) VALUES ('John', 'Lennon');
INSERT INTO myapp_person (first_name, last_name) VALUES ('Paul', 'McCartney');
Each SQL file, if given, is expected to contain valid SQL. The SQL files are
piped directly into the database after all of the models' table-creation
statements have been executed.
2007-04-13 01:01:57 +00:00
The SQL files are read by the ``sqlcustom``, ``sqlreset``, ``sqlall`` and
2006-05-19 05:07:33 +00:00
``reset`` commands in ``manage.py``. Refer to the `manage.py documentation`_
for more information.
2006-05-19 03:37:50 +00:00
2006-05-22 02:24:32 +00:00
Note that if you have multiple SQL data files, there's no guarantee of the
order in which they're executed. The only thing you can assume is that, by the
time your custom data files are executed, all the database tables already will
have been created.
2007-04-20 09:22:01 +00:00
.. _`manage.py documentation`: ../django-admin/#sqlcustom-appname-appname
2006-05-22 02:24:32 +00:00
Database-backend-specific SQL data
----------------------------------
There's also a hook for backend-specific SQL data. For example, you can have
separate initial-data files for PostgreSQL and MySQL. For each app, Django
looks for a file called ``<appname>/sql/<modelname>.<backend>.sql``, where
``<appname>`` is your app directory, ``<modelname>`` is the model's name in
lowercase and ``<backend>`` is the value of ``DATABASE_ENGINE`` in your
settings file (e.g., ``postgresql``, ``mysql``).
Backend-specific SQL data is executed before non-backend-specific SQL data. For
example, if your app contains the files ``sql/person.sql`` and
``sql/person.postgresql.sql`` and you're installing the app on PostgreSQL,
Django will execute the contents of ``sql/person.postgresql.sql`` first, then
``sql/person.sql``.