2005-07-13 09:25:57 +08:00
|
|
|
===============
|
|
|
|
Model reference
|
|
|
|
===============
|
|
|
|
|
2005-08-27 02:29:11 +08: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 09:25:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
The basics:
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
* Each model is a Python class that subclasses ``django.db.models.Model``.
|
2005-08-27 02:29:11 +08:00
|
|
|
* Each attribute of the model represents a database field.
|
2006-05-02 09:31:56 +08:00
|
|
|
* Model metadata (non-field information) goes in an inner class named
|
|
|
|
``Meta``.
|
|
|
|
* Metadata used for Django's admin site goes into an inner class named
|
|
|
|
``Admin``.
|
|
|
|
* With all of this, Django gives you an automatically-generated
|
|
|
|
database-access API, which is explained in the `Database API reference`_.
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
A companion to this document is the `official repository of model examples`_.
|
2006-05-05 10:57:19 +08:00
|
|
|
(In the Django source distribution, these examples are in the
|
|
|
|
``tests/modeltests`` directory.)
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _Database API reference: http://www.djangoproject.com/documentation/db_api/
|
|
|
|
.. _official repository of model examples: http://www.djangoproject.com/documentation/models/
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Quick example
|
2005-08-27 02:29:11 +08:00
|
|
|
=============
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
This example model defines a ``Person``, which has a ``first_name`` and
|
|
|
|
``last_name``::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.db import models
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(maxlength=30)
|
|
|
|
last_name = models.CharField(maxlength=30)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
The above ``Person`` model would create a database table like this::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Some technical notes:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
* The name of the table, ``myapp_person``, is automatically derived from
|
|
|
|
some model metadata but can be overridden. See _`Table names` below.
|
|
|
|
* An ``id`` field is added automatically, but this behavior can be
|
2006-05-09 23:21:28 +08:00
|
|
|
overriden. See `Automatic primary key fields`_ below.
|
2006-05-02 09:31:56 +08: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 09:44:35 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _settings file: http://www.djangoproject.com/documentation/settings/
|
2005-11-14 09:44:35 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Fields
|
|
|
|
======
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Example::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Musician(models.Model):
|
|
|
|
first_name = models.CharField(maxlength=50)
|
|
|
|
last_name = models.CharField(maxlength=50)
|
|
|
|
instrument = models.CharField(maxlength=100)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Album(models.Model):
|
|
|
|
artist = models.ForeignKey(Musician)
|
|
|
|
name = models.CharField(maxlength=100)
|
|
|
|
release_date = models.DateField()
|
|
|
|
num_stars = models.IntegerField()
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Field name restrictions
|
|
|
|
-----------------------
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Django places only two restrictions on model field names:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Example(models.Model):
|
|
|
|
pass = models.IntegerField() # 'pass' is a reserved word!
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Example(models.Model):
|
|
|
|
foo__bar = models.IntegerField() 'foo__bar' has two underscores!
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:59:39 +08:00
|
|
|
SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Field types
|
|
|
|
-----------
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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
|
|
|
|
manipulators.
|
2005-12-09 09:53:30 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Here are all available field types:
|
2005-12-09 09:53:30 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``AutoField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-12-09 09:53:30 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 23:21:28 +08:00
|
|
|
`Automatic primary key fields`_.
|
2005-12-09 09:53:30 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``BooleanField``
|
|
|
|
~~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A true/false field.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as a checkbox.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``CharField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A string field, for small- to large-sized strings.
|
2005-11-14 09:44:35 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
For large amounts of text, use ``TextField``.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` (a single-line input).
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``CharField`` has an extra required argument, ``maxlength``, the maximum length
|
|
|
|
(in characters) of the field. The maxlength is enforced at the database level
|
|
|
|
and in Django's validation.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``CommaSeparatedIntegerField``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A field of integers separated by commas. As in ``CharField``, the ``maxlength``
|
|
|
|
argument is required.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``DateField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-07-20 01:20:37 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A date field. Has a few extra optional arguments:
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
====================== ===================================================
|
|
|
|
Argument Description
|
|
|
|
====================== ===================================================
|
|
|
|
``auto_now`` Automatically set the field to now every time the
|
|
|
|
object is saved. Useful for "last-modified"
|
|
|
|
timestamps.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``auto_now_add`` Automatically set the field to now when the object
|
|
|
|
is first created. Useful for creation of
|
|
|
|
timestamps.
|
|
|
|
====================== ===================================================
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` with a JavaScript
|
|
|
|
calendar and a shortcut for "Today."
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``DateTimeField``
|
|
|
|
~~~~~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A date and time field. Takes the same extra options as ``DateField``.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as two ``<input type="text">`` fields, with
|
|
|
|
JavaScript shortcuts.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``EmailField``
|
|
|
|
~~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A ``CharField`` that checks that the value is a valid e-mail address.
|
|
|
|
This doesn't accept ``maxlength``.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``FileField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A file-upload field.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Has an extra required argument, ``upload_to``, a local filesystem path to
|
|
|
|
which files should be upload. 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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="file">`` (a file-upload widget).
|
2005-10-20 21:22:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few
|
|
|
|
steps:
|
2005-10-20 21:22:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
|
2006-05-22 13:04:40 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
2. Add the ``FileField`` or ``ImageField`` to your model, making sure
|
2006-05-22 13:04:40 +08:00
|
|
|
to define the ``upload_to`` option to tell Django to which
|
|
|
|
subdirectory of ``MEDIA_ROOT`` it should upload files.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
3. All that will be stored in your database is a path to the file
|
2006-05-22 13:04:40 +08:00
|
|
|
(relative to ``MEDIA_ROOT``). You'll must likely want to use the
|
|
|
|
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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``FilePathField``
|
|
|
|
~~~~~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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
|
|
|
|
required:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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:
|
|
|
|
``"foo.*\.txt^"``, which will match a file called
|
|
|
|
``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``recursive`` Optional. Either ``True`` or ``False``. Default is
|
|
|
|
``False``. Specifies whether all subdirectories of
|
|
|
|
``path`` should be included.
|
|
|
|
====================== ===================================================
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Of course, these arguments can be used together.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The one potential gotcha is that ``match`` applies to the base filename,
|
|
|
|
not the full path. So, this example::
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
FilePathField(path="/home/images", match="foo.*", recursive=True)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``FloatField``
|
|
|
|
~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A floating-point number. Has two **required** arguments:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
====================== ===================================================
|
|
|
|
Argument Description
|
|
|
|
====================== ===================================================
|
|
|
|
``max_digits`` The maximum number of digits allowed in the number.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``decimal_places`` The number of decimal places to store with the
|
|
|
|
number.
|
|
|
|
====================== ===================================================
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
For example, to store numbers up to 999 with a resolution of 2 decimal places,
|
|
|
|
you'd use::
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
models.FloatField(..., max_digits=5, decimal_places=2)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
And to store numbers up to approximately one billion with a resolution of 10
|
|
|
|
decimal places::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
models.FloatField(..., max_digits=19, decimal_places=10)
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` (a single-line input).
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``ImageField``
|
|
|
|
~~~~~~~~~~~~~~
|
2005-10-10 22:00:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Like ``FileField``, but validates that the uploaded object is a valid
|
|
|
|
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 22:00:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Requires the `Python Imaging Library`_.
|
2005-10-10 22:00:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _Python Imaging Library: http://www.pythonware.com/products/pil/
|
2005-09-30 21:49:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``IntegerField``
|
|
|
|
~~~~~~~~~~~~~~~~
|
2005-10-10 22:00:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
An integer.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` (a single-line input).
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``IPAddressField``
|
|
|
|
~~~~~~~~~~~~~~~~~~
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
An IP address, in string format (i.e. "24.124.1.30").
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` (a single-line input).
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``NullBooleanField``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this
|
|
|
|
instead of a ``BooleanField`` with ``null=True``.
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``PhoneNumberField``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``PositiveIntegerField``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Like an ``IntegerField``, but must be positive.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``PositiveSmallIntegerField``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Like a ``PositiveIntegerField``, but only allows values under a certain
|
|
|
|
(database-dependent) point.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``SlugField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
In the Django development version, you can specify ``maxlength``. If
|
|
|
|
``maxlength`` is not specified, Django will use a default length of 50. In
|
|
|
|
previous Django versions, there's no way to override the length of 50.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Implies ``db_index=True``.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Accepts an extra option, ``prepopulate_from``, which is a list of fields
|
|
|
|
from which to auto-populate the slug, via JavaScript, in the object's admin
|
|
|
|
form::
|
2005-10-10 22:00:20 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
models.SlugField(prepopulate_from=("pre_name", "name"))
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``prepopulate_from`` doesn't accept DateTimeFields.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents ``SlugField`` as an ``<input type="text">`` (a
|
|
|
|
single-line input).
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``SmallIntegerField``
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Like an ``IntegerField``, but only allows values under a certain
|
|
|
|
(database-dependent) point.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``TextField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A large text field.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as a ``<textarea>`` (a multi-line input).
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``TimeField``
|
|
|
|
~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A time. Accepts the same auto-population options as ``DateField`` and
|
|
|
|
``DateTimeField``.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` with some
|
|
|
|
JavaScript shortcuts.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``URLField``
|
|
|
|
~~~~~~~~~~~~
|
2006-02-18 02:15:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` (a single-line input).
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``USStateField``
|
|
|
|
~~~~~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
A two-letter U.S. state abbreviation.
|
2005-11-07 06:53:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The admin represents this as an ``<input type="text">`` (a single-line input).
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``XMLField``
|
|
|
|
~~~~~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _RelaxNG: http://www.relaxng.org/
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Field options
|
|
|
|
-------------
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The following arguments are available to all field types. All are optional.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``null``
|
|
|
|
~~~~~~~~
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
If ``True``, Django will store empty values as ``NULL`` in the database.
|
|
|
|
Default is ``False``.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Note that empty string values will always get stored as empty strings, not
|
|
|
|
as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
|
|
|
|
booleans and dates.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``blank``
|
|
|
|
~~~~~~~~~
|
|
|
|
|
|
|
|
If ``True``, the field is allowed to be blank.
|
|
|
|
|
|
|
|
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``
|
|
|
|
~~~~~~~~~~~
|
|
|
|
|
|
|
|
A list of 2-tuples to use as choices for this field.
|
|
|
|
|
|
|
|
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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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'),
|
|
|
|
)
|
|
|
|
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
|
|
|
|
|
|
|
|
or outside your model class altogether::
|
|
|
|
|
|
|
|
GENDER_CHOICES = (
|
|
|
|
('M', 'Male'),
|
|
|
|
('F', 'Female'),
|
|
|
|
)
|
|
|
|
class Foo(models.Model):
|
|
|
|
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
|
|
|
|
|
|
|
|
``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.
|
|
|
|
|
|
|
|
``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.
|
|
|
|
|
|
|
|
``default``
|
|
|
|
~~~~~~~~~~~
|
|
|
|
|
|
|
|
The default value for the field.
|
|
|
|
|
|
|
|
``editable``
|
|
|
|
~~~~~~~~~~~~
|
|
|
|
|
|
|
|
If ``False``, the field will not be editable in the admin. Default is ``True``.
|
|
|
|
|
|
|
|
``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.
|
|
|
|
|
|
|
|
``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.
|
|
|
|
|
|
|
|
``primary_key=True`` implies ``blank=False``, ``null=False`` and
|
|
|
|
``unique=True``. Only one primary key is allowed on an object.
|
|
|
|
|
|
|
|
``radio_admin``
|
|
|
|
~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
By default, Django's admin uses a select-box interface (<select>) for
|
|
|
|
fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
|
|
|
|
is set to ``True``, Django will use a radio-button interface instead.
|
|
|
|
|
|
|
|
Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
|
|
|
|
set.
|
|
|
|
|
|
|
|
``unique``
|
|
|
|
~~~~~~~~~~
|
|
|
|
|
|
|
|
If ``True``, this field must be unique throughout the table.
|
|
|
|
|
|
|
|
This is enforced at the database level and at the Django admin-form level.
|
|
|
|
|
|
|
|
``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``.
|
|
|
|
|
|
|
|
.. _validator docs: http://www.djangoproject.com/documentation/forms/#validators
|
|
|
|
|
|
|
|
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"``::
|
|
|
|
|
|
|
|
first_name = models.CharField("Person's first name", maxlength=30)
|
|
|
|
|
|
|
|
In this example, the verbose name is ``"first name"``::
|
|
|
|
|
|
|
|
first_name = models.CharField(maxlength=30)
|
|
|
|
|
|
|
|
``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-27 02:29:11 +08:00
|
|
|
|
|
|
|
Relationships
|
|
|
|
-------------
|
|
|
|
|
|
|
|
Clearly, the power of relational databases lies in relating tables to each
|
2006-05-02 09:31:56 +08:00
|
|
|
other. Django offers ways to define the three most common types of database
|
2005-08-27 02:29:11 +08: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.
|
|
|
|
|
|
|
|
``ForeignKey`` requires a positional argument: The class to which the model is
|
|
|
|
related.
|
|
|
|
|
2006-05-04 12:59:45 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
class Manufacturer(models.Model):
|
2005-08-27 02:29:11 +08:00
|
|
|
# ...
|
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
class Car(models.Model):
|
|
|
|
manufacturer = models.ForeignKey(Manufacturer)
|
2005-08-27 02:29:11 +08:00
|
|
|
# ...
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
To create a recursive relationship -- an object that has a many-to-one
|
2006-05-02 09:31:56 +08: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 12:59:45 +08:00
|
|
|
class Car(models.Model):
|
|
|
|
manufacturer = models.ForeignKey('Manufacturer')
|
2006-05-02 09:31:56 +08:00
|
|
|
# ...
|
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
class Manufacturer(models.Model):
|
2006-05-02 09:31:56 +08:00
|
|
|
# ...
|
2005-07-21 11:46:16 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Note, however, that support for strings around model names in ``ForeignKey`` is
|
|
|
|
quite new, and it can be buggy in some cases.
|
|
|
|
|
|
|
|
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 09:31:56 +08:00
|
|
|
should never have to deal with the database column name, unless you write
|
2006-05-04 12:59:45 +08: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 11:46:16 +08:00
|
|
|
|
2005-08-27 02:35:44 +08:00
|
|
|
See the `Many-to-one relationship model example`_ for a full example.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
.. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
|
|
|
|
|
|
|
|
``ForeignKey`` fields take a number of extra arguments for defining how the
|
|
|
|
relationship should work. All are optional:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-15 08:54:49 +08:00
|
|
|
======================= ============================================================
|
2005-07-19 04:53:02 +08:00
|
|
|
Argument Description
|
2005-07-15 08:54:49 +08:00
|
|
|
======================= ============================================================
|
2005-08-10 05:08:00 +08:00
|
|
|
``edit_inline`` If not ``False``, this related object is edited
|
2005-07-17 12:20:57 +08:00
|
|
|
"inline" on the related object's page. This means
|
|
|
|
that the object will not have its own admin
|
2006-05-02 09:31:56 +08:00
|
|
|
interface. Use either ``models.TABULAR`` or ``models.STACKED``,
|
2005-08-10 05:08:00 +08:00
|
|
|
which, respectively, designate whether the inline-editable
|
|
|
|
objects are displayed as a table or as a "stack" of
|
|
|
|
fieldsets.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``limit_choices_to`` A dictionary of lookup arguments and values (see
|
2005-07-17 12:20:57 +08:00
|
|
|
the `Database API reference`_) that limit the
|
|
|
|
available admin choices for this object. Use this
|
2006-05-02 09:31:56 +08:00
|
|
|
with ``models.LazyDate`` to limit choices of objects
|
2005-07-17 12:20:57 +08:00
|
|
|
by date. For example::
|
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
limit_choices_to = {'pub_date__lte': models.LazyDate()}
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
only allows the choice of related objects with a
|
|
|
|
``pub_date`` before the current date/time to be
|
|
|
|
chosen.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-06 08:26:24 +08: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 09:25:57 +08:00
|
|
|
Not compatible with ``edit_inline``.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``max_num_in_admin`` For inline-edited objects, this is the maximum
|
|
|
|
number of related objects to display in the admin.
|
2005-07-17 12:20:57 +08:00
|
|
|
Thus, if a pizza could only have up to 10
|
2005-07-13 09:25:57 +08:00
|
|
|
toppings, ``max_num_in_admin=10`` would ensure
|
|
|
|
that a user never enters more than 10 toppings.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
Note that this doesn't ensure more than 10 related
|
2006-05-04 12:59:45 +08:00
|
|
|
toppings ever get created. It simply controls the
|
|
|
|
admin interface; it doesn't enforce things at the
|
|
|
|
Python API level or database level.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``min_num_in_admin`` The minimum number of related objects displayed in
|
2005-07-17 12:20:57 +08:00
|
|
|
the admin. Normally, at the creation stage,
|
2005-07-13 09:25:57 +08:00
|
|
|
``num_in_admin`` inline objects are shown, and at
|
2005-07-17 12:20:57 +08:00
|
|
|
the edit stage ``num_extra_on_change`` blank
|
|
|
|
objects are shown in addition to all pre-existing
|
|
|
|
related objects. However, no fewer than
|
2005-07-13 09:25:57 +08:00
|
|
|
``min_num_in_admin`` related objects will ever be
|
|
|
|
displayed.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
|
|
|
``num_extra_on_change`` The number of extra blank related-object fields to
|
2005-07-13 09:25:57 +08:00
|
|
|
show at the change stage.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``num_in_admin`` The default number of inline objects to display
|
|
|
|
on the object page at the add stage.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``raw_id_admin`` Only display a field for the integer to be entered
|
2005-07-17 12:20:57 +08:00
|
|
|
instead of a drop-down menu. This is useful when
|
2005-07-13 09:25:57 +08:00
|
|
|
related to an object type that will have too many
|
2005-07-17 12:20:57 +08:00
|
|
|
rows to make a select box practical.
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
Not used with ``edit_inline``.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``related_name`` The name to use for the relation from the related
|
2006-05-04 12:59:45 +08:00
|
|
|
object back to this one. See the
|
|
|
|
`related objects documentation`_ for a full
|
|
|
|
explanation and example.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-15 08:42:28 +08:00
|
|
|
``to_field`` The field on the related object that the relation
|
2005-08-27 02:29:11 +08:00
|
|
|
is to. By default, Django uses the primary key of
|
|
|
|
the related object.
|
2005-07-15 08:54:49 +08:00
|
|
|
======================= ============================================================
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-07-17 12:20:57 +08:00
|
|
|
.. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
|
2006-05-04 12:59:45 +08:00
|
|
|
.. _related objects documentation: http://www.djangoproject.com/documentation/db_api/#related-objects
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
Many-to-many relationships
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-11-20 04:20:13 +08:00
|
|
|
To define a many-to-many relationship, use ``ManyToManyField``. You use it just
|
2005-08-27 02:29:11 +08:00
|
|
|
like any other ``Field`` type: by including it as a class attribute of your
|
|
|
|
model.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
``ManyToManyField`` requires a positional argument: The class to which the
|
|
|
|
model is related.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Topping(models.Model):
|
2005-08-27 02:29:11 +08:00
|
|
|
# ...
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Pizza(models.Model):
|
2005-08-27 02:29:11 +08:00
|
|
|
# ...
|
2006-05-02 09:31:56 +08:00
|
|
|
toppings = models.ManyToManyField(Topping)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
As with ``ForeignKey``, a relationship to self can be defined by using the
|
2006-05-04 12:59:45 +08:00
|
|
|
string ``'self'`` instead of the model name, and you can refer to as-yet
|
|
|
|
undefined models by using a string containing the model name.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08: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-27 02:29:11 +08: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 12:59:45 +08: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 12:20:57 +08:00
|
|
|
|
2005-08-27 02:35:44 +08:00
|
|
|
See the `Many-to-many relationship model example`_ for a full example.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
|
|
|
.. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
|
|
|
|
|
|
|
|
``ManyToManyField`` objects take a number of extra arguments for defining how
|
|
|
|
the relationship should work. All are optional:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
======================= ============================================================
|
2005-07-19 04:53:02 +08:00
|
|
|
Argument Description
|
2005-07-16 04:37:03 +08:00
|
|
|
======================= ============================================================
|
2006-05-04 12:59:45 +08:00
|
|
|
``related_name`` See the description under ``ForeignKey`` above.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
|
|
|
``filter_interface`` Use a nifty unobtrusive Javascript "filter" interface
|
|
|
|
instead of the usability-challenged ``<select multiple>``
|
|
|
|
in the admin form for this object. The value should be
|
2006-05-02 09:31:56 +08:00
|
|
|
``models.HORIZONTAL`` or ``models.VERTICAL`` (i.e.
|
2005-07-17 12:20:57 +08:00
|
|
|
should the interface be stacked horizontally or
|
2005-07-16 04:37:03 +08:00
|
|
|
vertically).
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-05 03:00:20 +08:00
|
|
|
``limit_choices_to`` See the description under ``ForeignKey`` above.
|
2005-10-30 22:35:44 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
``symmetrical`` Only used in the definition of ManyToManyFields on self.
|
|
|
|
Consider the following model:
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
friends = models.ManyToManyField("self")
|
|
|
|
|
|
|
|
When Django processes this model, it identifies that it has
|
2006-05-04 12:59:45 +08: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.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
======================= ============================================================
|
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
One-to-one relationships
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
The semantics of one-to-one relationships will be changing soon, so we don't
|
|
|
|
recommend you use them. If that doesn't scare you away, keep reading.
|
|
|
|
|
2005-08-27 02:29:11 +08: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 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
This is most useful on the primary key of an object when that object "extends"
|
|
|
|
another object in some way.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
``OneToOneField`` requires a positional argument: The class to which the
|
|
|
|
model is related.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08: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-16 04:37:03 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
This ``OneToOneField`` will actually replace the primary key ``id`` field
|
|
|
|
(since one-to-one relations share the same primary key), and will be displayed
|
|
|
|
as a read-only field when you edit an object in the admin interface:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:35:44 +08:00
|
|
|
See the `One-to-one relationship model example`_ for a full example.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
.. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Meta options
|
2005-08-27 02:29:11 +08:00
|
|
|
============
|
2005-08-16 00:15:26 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Give your model metadata by using an inner ``class Meta``, like so::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Foo(models.Model):
|
|
|
|
bar = models.CharField(maxlength=30)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class Meta:
|
|
|
|
# ...
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Model metadata is "anything that's not a field", such as ordering options, etc.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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 12:20:57 +08:00
|
|
|
|
2005-08-27 02:29:11 +08:00
|
|
|
``db_table``
|
2006-05-02 09:31:56 +08:00
|
|
|
------------
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
The name of the database table to use for the model::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
db_table = 'music_album'
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
If this isn't given, Django will use ``app_label + '_' + model_class_name``.
|
2006-05-04 12:59:45 +08:00
|
|
|
See "Table names" below for more.
|
2005-11-14 09:44:35 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
|
|
|
``get_latest_by``
|
2006-05-02 09:31:56 +08:00
|
|
|
-----------------
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
get_latest_by = "order_date"
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
See the `docs for latest()`_ for more.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
.. _docs for latest(): http://www.djangoproject.com/documentation/db_api/#latest-field-name-none
|
2005-08-27 02:29:11 +08:00
|
|
|
|
|
|
|
``order_with_respect_to``
|
2006-05-02 09:31:56 +08: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 12:59:45 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
class Answer(models.Model):
|
|
|
|
question = models.ForeignKey(Question)
|
|
|
|
# ...
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
class Meta:
|
|
|
|
order_with_respect_to = 'question'
|
2005-08-27 02:29:11 +08:00
|
|
|
|
|
|
|
``ordering``
|
2006-05-02 09:31:56 +08:00
|
|
|
------------
|
|
|
|
|
|
|
|
The default ordering for the object, for use when obtaining lists of objects::
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
ordering = ['-order_date']
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
For example, to order by a ``pub_date`` field ascending, use this::
|
2006-04-13 09:45:15 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
ordering = ['pub_date']
|
2006-04-13 09:45:15 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
To order by ``pub_date`` descending, use this::
|
2006-04-13 09:45:15 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
ordering = ['-pub_date']
|
2006-04-13 09:45:15 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
To order by ``pub_date`` descending, then by ``author`` ascending, use this::
|
2006-04-13 09:45:15 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
ordering = ['-pub_date', 'author']
|
2006-04-13 09:45:15 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
See `Specifying ordering`_ for more examples.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Note that, regardless of how many fields are in ``ordering``, the admin
|
|
|
|
site uses only the first field.
|
2006-04-13 09:46:08 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
|
2005-08-27 02:29:11 +08:00
|
|
|
|
|
|
|
``permissions``
|
2006-05-02 09:31:56 +08:00
|
|
|
---------------
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
|
|
|
``unique_together``
|
2006-05-02 09:31:56 +08:00
|
|
|
-------------------
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Sets of field names that, taken together, must be unique::
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08: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-27 02:29:11 +08:00
|
|
|
|
|
|
|
``verbose_name``
|
2006-05-02 09:31:56 +08:00
|
|
|
----------------
|
|
|
|
|
|
|
|
A human-readable name for the object, singular::
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
verbose_name = "pizza"
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
If this isn't given, Django will use a munged version of the class name:
|
|
|
|
``CamelCase`` becomes ``camel case``.
|
2005-08-27 02:29:11 +08:00
|
|
|
|
|
|
|
``verbose_name_plural``
|
2006-05-02 09:31:56 +08:00
|
|
|
-----------------------
|
|
|
|
|
|
|
|
The plural name for the object::
|
|
|
|
|
|
|
|
verbose_name_plural = "stories"
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
If this isn't given, Django will use ``verbose_name + "s"``.
|
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Table names
|
|
|
|
===========
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08: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 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08: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 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
To override the database table name, use the ``db_table`` parameter in
|
|
|
|
``class Meta``.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
Automatic primary key fields
|
|
|
|
============================
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-04 12:59:45 +08: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 09:25:57 +08:00
|
|
|
|
|
|
|
Admin options
|
|
|
|
=============
|
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
If you want your model to be visible to Django's admin site, give your model an
|
|
|
|
inner ``"class Admin"``, like so::
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(maxlength=30)
|
|
|
|
last_name = models.CharField(maxlength=30)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
class Admin:
|
2006-05-04 12:59:45 +08:00
|
|
|
# Admin options go here
|
|
|
|
pass
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
The ``Admin`` class tells Django how to display the model in the admin site.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Here's a list of all possible ``Admin`` options. None of these options are
|
|
|
|
required. To use an admin interface without specifying any options, use
|
|
|
|
``pass``, like so::
|
|
|
|
|
|
|
|
class Admin:
|
|
|
|
pass
|
|
|
|
|
|
|
|
Adding ``class Admin`` to a model is completely optional.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-07-17 12:20:57 +08:00
|
|
|
``date_hierarchy``
|
2006-05-04 12:59:45 +08:00
|
|
|
------------------
|
|
|
|
|
|
|
|
Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
|
|
|
|
your model, and the change list page will include a date-based drilldown
|
|
|
|
navigation by that field.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Example::
|
|
|
|
|
|
|
|
date_hierarchy = 'pub_date'
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``fields``
|
2006-05-04 12:59:45 +08:00
|
|
|
----------
|
|
|
|
|
|
|
|
Set ``fields`` to control the layout of admin "add" and "change" pages.
|
|
|
|
|
|
|
|
``fields`` is a list of two-tuples, in which each two-tuple represents a
|
|
|
|
``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the
|
|
|
|
form.)
|
|
|
|
|
|
|
|
The two-tuples are in the format ``(name, field_options)``, where ``name`` is a
|
|
|
|
string representing the title of the fieldset and ``field_options`` is a
|
|
|
|
dictionary of information about the fieldset, including a list of fields to be
|
|
|
|
displayed in it.
|
|
|
|
|
|
|
|
A full example, taken from the ``django.contrib.flatpages.FlatPage`` model::
|
|
|
|
|
|
|
|
class Admin:
|
|
|
|
fields = (
|
|
|
|
(None, {
|
|
|
|
'fields': ('url', 'title', 'content', 'sites')
|
|
|
|
}),
|
|
|
|
('Advanced options', {
|
|
|
|
'classes': 'collapse',
|
|
|
|
'fields' : ('enable_comments', 'registration_required', 'template_name')
|
|
|
|
}),
|
|
|
|
)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
This results in an admin page that looks like:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
.. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
If ``fields`` isn't given, Django will default to displaying each field that
|
|
|
|
isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
|
|
|
|
the same order as the fields are defined in the model.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-09 23:21:28 +08:00
|
|
|
The ``field_options`` dictionary can have the following keys:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
``fields``
|
|
|
|
~~~~~~~~~~
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
A tuple of field names to display in this fieldset. This key is required.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Example::
|
|
|
|
|
|
|
|
{
|
|
|
|
'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
|
|
|
|
}
|
|
|
|
|
|
|
|
To display multiple fields on the same line, wrap those fields in their own
|
|
|
|
tuple. In this example, the ``first_name`` and ``last_name`` fields will
|
|
|
|
display on the same line::
|
|
|
|
|
|
|
|
{
|
|
|
|
'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
|
|
|
|
}
|
|
|
|
|
|
|
|
``classes``
|
|
|
|
~~~~~~~~~~~
|
|
|
|
|
|
|
|
A string containing extra CSS classes to apply to the fieldset.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
{
|
|
|
|
'classes': 'wide',
|
|
|
|
}
|
|
|
|
|
|
|
|
Apply multiple classes by separating them with spaces. Example::
|
|
|
|
|
|
|
|
{
|
|
|
|
'classes': 'wide extrapretty',
|
|
|
|
}
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Two useful classes defined by the default admin-site stylesheet are
|
|
|
|
``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will be
|
|
|
|
initially collapsed in the admin and replaced with a small "click to expand"
|
|
|
|
link. Fieldsets with the ``wide`` style will be given extra horizontal space.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
``description``
|
|
|
|
~~~~~~~~~~~~~~~
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
A string of optional extra text to be displayed at the top of each fieldset,
|
|
|
|
under the heading of the fieldset. It's used verbatim, so you can use any HTML
|
|
|
|
and you must escape any special HTML characters (such as ampersands) yourself.
|
2005-07-21 11:46:16 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``js``
|
2006-05-04 12:59:45 +08:00
|
|
|
------
|
|
|
|
|
|
|
|
A list of strings representing URLs of JavaScript files to link into the admin
|
|
|
|
screen via ``<script src="">`` tags. This can be used to tweak a given type of
|
|
|
|
admin page in JavaScript or to provide "quick links" to fill in default values
|
|
|
|
for certain fields.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``list_display``
|
2006-05-04 12:59:45 +08:00
|
|
|
----------------
|
|
|
|
|
|
|
|
Set ``list_display`` to control which fields are displayed on the change list
|
|
|
|
page of the admin.
|
|
|
|
|
|
|
|
Example::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
list_display = ('first_name', 'last_name')
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
If you don't set ``list_display``, the admin site will display a single column
|
|
|
|
that displays the ``__str__()`` representation of each object.
|
2005-09-20 10:37:39 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
A few special cases to note about ``list_display``:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
* If the field is a ``ForeignKey``, Django will display the ``__str__()``
|
|
|
|
of the related object.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
* ``ManyToManyField`` fields aren't supported, because that would entail
|
|
|
|
executing a separate SQL statement for each row in the table.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
* If the field is a ``BooleanField``, Django will display a pretty "on" or
|
|
|
|
"off" icon instead of ``True`` or ``False``.
|
2005-09-20 10:37:39 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
* If the string given is a method of the model, Django will call it and
|
|
|
|
display the output. This method should have a ``short_description``
|
|
|
|
function attribute, for use as the header for the field.
|
|
|
|
|
|
|
|
Here's a full example model::
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
name = models.CharField(maxlength=50)
|
|
|
|
birthday = models.DateField()
|
|
|
|
|
|
|
|
class Admin:
|
|
|
|
list_display = ('name', 'decade_born_in')
|
|
|
|
|
|
|
|
def decade_born_in(self):
|
|
|
|
return self.birthday.strftime('%Y')[:3] + "0's"
|
|
|
|
decade_born_in.short_description = 'Birth decade'
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``list_filter``
|
2006-05-04 12:59:45 +08:00
|
|
|
---------------
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
Set ``list_filter`` to activate filters in the right sidebar of the change list
|
|
|
|
page of the admin. This should be a list of field names, and each specified
|
|
|
|
field should be either a ``BooleanField``, ``DateField``, ``DateTimeField``
|
|
|
|
or ``ForeignKey``.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
This example, taken from the ``django.contrib.auth.models.User`` model, shows
|
|
|
|
how both ``list_display`` and ``list_filter`` work::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
class Admin:
|
|
|
|
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
|
|
|
|
list_filter = ('is_staff', 'is_superuser')
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
The above code results in an admin change list page that looks like this:
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
.. image:: http://media.djangoproject.com/img/doc/users_changelist.png
|
|
|
|
|
|
|
|
(This example also has ``search_fields`` defined. See below.)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-11-07 07:08:29 +08:00
|
|
|
``list_select_related``
|
2006-05-04 12:59:45 +08:00
|
|
|
-----------------------
|
|
|
|
|
|
|
|
Set ``list_select_related`` to tell Django to use ``select_related()`` in
|
|
|
|
retrieving the list of objects on the admin change list page. This can save you
|
|
|
|
a bunch of database queries.
|
|
|
|
|
|
|
|
The value should be either ``True`` or ``False``. Default is ``False``.
|
|
|
|
|
|
|
|
Note that Django will use ``select_related()``, regardless of this setting,
|
|
|
|
if one of the ``list_display`` fields is a ``ForeignKey``.
|
|
|
|
|
|
|
|
For more on ``select_related()``, see `the select_related() docs`_.
|
2005-11-07 07:08:29 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
.. _the select_related() docs: http://www.djangoproject.com/documentation/db_api/#select-related
|
2005-11-07 07:08:29 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``ordering``
|
2006-05-04 12:59:45 +08:00
|
|
|
------------
|
|
|
|
|
|
|
|
Set ``ordering`` to specify how objects on the admin change list page should be
|
|
|
|
ordered. This should be a list or tuple in the same format as a model's
|
|
|
|
``ordering`` parameter.
|
|
|
|
|
|
|
|
If this isn't provided, the Django admin will use the model's default ordering.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``save_as``
|
2006-05-04 12:59:45 +08:00
|
|
|
-----------
|
|
|
|
|
|
|
|
Set ``save_as`` to enable a "save as" feature on admin change forms.
|
|
|
|
|
|
|
|
Normally, objects have three save options: "Save", "Save and continue editing"
|
|
|
|
and "Save and add another". If ``save_as`` is ``True``, "Save and add another"
|
|
|
|
will be replaced by a "Save as" button.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-04 12:59:45 +08:00
|
|
|
"Save as" means the object will be saved as a new object (with a new ID),
|
|
|
|
rather than the old object.
|
|
|
|
|
|
|
|
By default, ``save_as`` is set to ``False``.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``save_on_top``
|
2006-05-04 12:59:45 +08:00
|
|
|
---------------
|
|
|
|
|
|
|
|
Set ``save_on_top`` to add save buttons across the top of your admin change
|
|
|
|
forms.
|
|
|
|
|
|
|
|
Normally, the save buttons appear only at the bottom of the forms. If you set
|
|
|
|
``save_on_top``, the buttons will appear both on the top and the bottom.
|
|
|
|
|
|
|
|
By default, ``save_on_top`` is set to ``False``.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
``search_fields``
|
2006-05-04 12:59:45 +08:00
|
|
|
-----------------
|
|
|
|
|
|
|
|
Set ``search_fields`` to enable a search box on the admin change list page.
|
|
|
|
This should be set to a list of field names that will be searched whenever
|
|
|
|
somebody submits a search query in that text box.
|
|
|
|
|
|
|
|
These fields should be some kind of text field, such as ``CharField`` or
|
|
|
|
``TextField``.
|
|
|
|
|
|
|
|
When somebody does a search in the admin search box, Django splits the search
|
|
|
|
query into words and returns all objects that contain each of the words, case
|
|
|
|
insensitive, where each word must be in at least one of ``search_fields``. For
|
|
|
|
example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a
|
|
|
|
user searches for ``john lennon``, Django will do the equivalent of this SQL
|
|
|
|
``WHERE`` clause::
|
|
|
|
|
|
|
|
WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
|
|
|
|
AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Managers
|
|
|
|
========
|
|
|
|
|
2006-05-05 09:56:29 +08: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 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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.
|
|
|
|
|
2006-05-09 23:21:28 +08:00
|
|
|
.. _Retrieving objects: http://www.djangoproject.com/documentation/db_api/#retrieving-objects
|
|
|
|
|
2006-05-05 09:56:29 +08: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 09:31:56 +08:00
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
#...
|
|
|
|
people = models.Manager()
|
|
|
|
|
2006-05-05 09:56:29 +08: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 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
Custom Managers
|
|
|
|
---------------
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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
|
|
|
|
that act on a single instance of a model object -- use _`Model methods`, not
|
|
|
|
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):
|
|
|
|
question = models.CharField(maxlength=200)
|
|
|
|
poll_date = models.DateField()
|
|
|
|
objects = PollManager()
|
|
|
|
|
|
|
|
class Response(models.Model):
|
|
|
|
poll = models.ForeignKey(Poll)
|
|
|
|
person_name = models.CharField(maxlength=50)
|
|
|
|
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):
|
|
|
|
title = models.CharField(maxlength=100)
|
|
|
|
author = models.CharField(maxlength=50)
|
|
|
|
|
|
|
|
...the statement ``Book.objects.all()`` will return all books in the database.
|
|
|
|
|
2006-05-09 23:21:28 +08:00
|
|
|
You can override a ``Manager``\'s base ``QuerySet`` by overriding the
|
2006-05-05 09:56:29 +08:00
|
|
|
``Manager.get_query_set()`` method. ``get_query_set()`` should return a
|
|
|
|
``QuerySet`` with the properties you require.
|
|
|
|
|
2006-05-09 23:21:28 +08:00
|
|
|
For example, the following model has *two* ``Manager``\s -- one that returns
|
2006-05-05 09:56:29 +08: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-10 05:32:56 +08:00
|
|
|
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
# Then hook it into the Book model explicitly.
|
|
|
|
class Book(models.Model):
|
|
|
|
title = models.CharField(maxlength=100)
|
|
|
|
author = models.CharField(maxlength=50)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
objects = models.Manager() # The default manager.
|
|
|
|
dahl_objects = DahlBookManager() # The Dahl-specific manager.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
Book.dahl_objects.all()
|
|
|
|
Book.dahl_objects.filter(title='Matilda')
|
|
|
|
Book.dahl_objects.count()
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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 09:31:56 +08:00
|
|
|
|
|
|
|
class MaleManager(models.Manager):
|
|
|
|
def get_query_set(self):
|
2006-05-10 05:32:56 +08:00
|
|
|
return super(MaleManager, self).get_query_set().filter(sex='M')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
class FemaleManager(models.Manager):
|
|
|
|
def get_query_set(self):
|
2006-05-10 05:32:56 +08:00
|
|
|
return super(FemaleManager, self).get_query_set().filter(sex='F')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
class Person(models.Model):
|
2006-05-05 09:56:29 +08:00
|
|
|
first_name = models.CharField(maxlength=50)
|
|
|
|
last_name = models.CharField(maxlength=50)
|
|
|
|
sex = models.CharField(maxlength=1, choices=(('M', 'Male'), ('F', 'Female')))
|
2006-05-02 09:31:56 +08:00
|
|
|
people = models.Manager()
|
|
|
|
men = MaleManager()
|
|
|
|
women = FemaleManager()
|
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
This example allows you to request ``Person.men.all()``, ``Person.women.all()``,
|
2006-05-02 09:31:56 +08:00
|
|
|
and ``Person.people.all()``, yielding predictable results.
|
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
If you use custom ``Manager`` objects, take note that the first ``Manager``
|
|
|
|
Django encounters (in order by which they're defined in the model) has a
|
|
|
|
special status. Django interprets the first ``Manager`` defined in a class as
|
|
|
|
the "default" ``Manager``. Certain operations -- such as Django's admin site --
|
|
|
|
use the default ``Manager`` to obtain lists of objects, so it's generally a
|
|
|
|
good idea for the first ``Manager`` to be relatively unfiltered. In the last
|
|
|
|
example, the ``people`` ``Manager`` is defined first -- so it's the default
|
|
|
|
``Manager``.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2005-07-16 04:37:03 +08:00
|
|
|
Model methods
|
|
|
|
=============
|
|
|
|
|
2006-05-05 09:56:29 +08: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-16 04:37:03 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
This is a valuable technique for keeping business logic in one place -- the
|
|
|
|
model.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
For example, this model has a few custom methods::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(maxlength=50)
|
|
|
|
last_name = models.CharField(maxlength=50)
|
|
|
|
birth_date = models.DateField()
|
|
|
|
address = models.CharField(maxlength=100)
|
|
|
|
city = models.CharField(maxlength=50)
|
|
|
|
state = models.USStateField() # Yes, this is America-centric...
|
2005-07-16 04:37:03 +08:00
|
|
|
|
2006-05-06 02:31:16 +08: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-16 04:37:03 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
The last method in this example is a *property*. `Read more about properties`_.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
.. _Read more about properties: http://www.python.org/download/releases/2.2/descrintro/#property
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
A few object methods have special meaning:
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
``__str__``
|
|
|
|
-----------
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
``__str__()`` is a Python "magic method" that defines what should be returned
|
|
|
|
if you call ``str()`` on the object. Django uses ``str(obj)`` 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.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
For example::
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(maxlength=50)
|
|
|
|
last_name = models.CharField(maxlength=50)
|
2005-08-27 02:29:11 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
def __str__(self):
|
|
|
|
return '%s %s' % (self.first_name, self.last_name)
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
``get_absolute_url``
|
2005-07-16 04:37:03 +08:00
|
|
|
--------------------
|
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
Define a ``get_absolute_url()`` method to tell Django how to calculate the
|
|
|
|
URL for an object. For example::
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
def get_absolute_url(self):
|
|
|
|
return "/people/%i/" % self.id
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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-16 04:37:03 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
Also, a couple of other bits of Django, such as the syndication-feed framework,
|
|
|
|
use ``get_absolute_url()`` as a convenience to reward people who've defined the
|
|
|
|
method.
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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-16 04:37:03 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
<a href="/people/{{ object.id }}/">{{ object.name }}</a>
|
2006-05-04 12:59:45 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
But this template code is good::
|
2005-07-16 04:37:03 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
|
2005-07-17 12:20:57 +08:00
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
(Yes, we know ``get_absolute_url()`` couples URLs to models, which violates the
|
|
|
|
DRY principle, because URLs are defined both in a URLconf and in the model.
|
|
|
|
This is a rare case in which we've intentionally violated that principle for
|
|
|
|
the sake of convenience. With that said, we're working on an even cleaner way
|
|
|
|
of specifying URLs in a more DRY fashion.)
|
2005-08-27 03:02:07 +08:00
|
|
|
|
2005-11-21 01:33:40 +08:00
|
|
|
Executing custom SQL
|
|
|
|
--------------------
|
|
|
|
|
|
|
|
Feel free to write custom SQL statements in custom model methods and
|
2006-05-05 09:56:29 +08: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-21 01:33:40 +08:00
|
|
|
|
|
|
|
def my_custom_sql(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.db import connection
|
|
|
|
cursor = connection.cursor()
|
2005-11-21 01:33:40 +08:00
|
|
|
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
|
|
|
|
row = cursor.fetchone()
|
|
|
|
return row
|
|
|
|
|
2006-05-05 09:56:29 +08:00
|
|
|
``connection`` and ``cursor`` simply use the standard `Python DB-API`_. If
|
|
|
|
you're not familiar with the Python DB-API, note that the SQL statement in
|
2005-11-21 01:33:40 +08:00
|
|
|
``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
|
2006-05-05 09:56:29 +08:00
|
|
|
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-21 01:33:40 +08:00
|
|
|
|
2006-03-23 07:06:22 +08:00
|
|
|
A final note: If all you want to do is a custom ``WHERE`` clause, you can just
|
|
|
|
just the ``where``, ``tables`` and ``params`` arguments to the standard lookup
|
|
|
|
API. See `Other lookup options`_.
|
|
|
|
|
2005-11-21 01:33:40 +08:00
|
|
|
.. _Python DB-API: http://www.python.org/peps/pep-0249.html
|
2006-05-02 09:31:56 +08:00
|
|
|
.. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables
|
2005-11-21 01:33:40 +08:00
|
|
|
|
2006-05-22 11:01:02 +08: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):
|
|
|
|
name = models.CharField(maxlength=100)
|
|
|
|
tagline = models.TextField()
|
|
|
|
|
|
|
|
def save(self):
|
|
|
|
do_something()
|
|
|
|
super(Blog, self).save() # Call the "real" save() method.
|
|
|
|
do_something_else()
|
|
|
|
|
|
|
|
You can also prevent saving::
|
|
|
|
|
|
|
|
class Blog(models.Model):
|
|
|
|
name = models.CharField(maxlength=100)
|
|
|
|
tagline = models.TextField()
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
.. _database API docs: http://www.djangoproject.com/documentation/db_api/
|
|
|
|
|
2006-05-05 09:56:29 +08: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-27 03:02:07 +08:00
|
|
|
Using models
|
|
|
|
============
|
|
|
|
|
2006-05-05 09:56:29 +08: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-27 03:02:07 +08:00
|
|
|
|
2006-05-05 09:56:29 +08: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-27 03:02:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
INSTALLED_APPS = (
|
|
|
|
#...
|
2006-05-05 09:56:29 +08:00
|
|
|
'mysite.myapp',
|
2006-05-02 09:31:56 +08:00
|
|
|
#...
|
|
|
|
)
|
2006-05-19 11:37:50 +08:00
|
|
|
|
2006-05-19 13:07:33 +08: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.
|
|
|
|
|
|
|
|
The SQL files are read by the ``sqlinitialdata``, ``sqlreset``, ``sqlall`` and
|
|
|
|
``reset`` commands in ``manage.py``. Refer to the `manage.py documentation`_
|
|
|
|
for more information.
|
2006-05-19 11:37:50 +08:00
|
|
|
|
2006-05-22 10:24:32 +08: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.
|
|
|
|
|
2006-05-19 11:37:50 +08:00
|
|
|
.. _`manage.py documentation`: http://www.djangoproject.com/documentation/django_admin/#sqlinitialdata-appname-appname
|
2006-05-22 10:24:32 +08: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``.
|