===============
Model reference
===============
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.
The basics:
    * Each model is a Python class that subclasses ``django.db.models.Model``.
    * Each attribute of the model represents a database field.
    * 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`_.
A companion to this document is the `official repository of model examples`_.
(In the Django source distribution, these examples are in the
``tests/modeltests`` directory.)
.. _Database API reference: ../db-api/
.. _official repository of model examples: ../models/
Quick example
=============
This example model defines a ``Person``, which has a ``first_name`` and
``last_name``::
    from django.db import models
    class Person(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
``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.
The above ``Person`` model would create a database table like this::
    CREATE TABLE myapp_person (
        "id" serial NOT NULL PRIMARY KEY,
        "first_name" varchar(30) NOT NULL,
        "last_name" varchar(30) NOT NULL
    );
Some technical notes:
    * 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
      overridden. See `Automatic primary key fields`_ below.
    * 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`_.
.. _settings file: ../settings/
Fields
======
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.
Example::
    class Musician(models.Model):
        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
        instrument = models.CharField(max_length=100)
    class Album(models.Model):
        artist = models.ForeignKey(Musician)
        name = models.CharField(max_length=100)
        release_date = models.DateField()
        num_stars = models.IntegerField()
Field name restrictions
-----------------------
Django places only two restrictions on model field names:
    1. A field name cannot be a Python reserved word, because that would result
       in a Python syntax error. For example::
           class Example(models.Model):
               pass = models.IntegerField() # 'pass' is a reserved word!
    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::
           class Example(models.Model):
               foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
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.
SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
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.
Field types
-----------
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:
    * 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. ````).
    * The minimal validation requirements, used in Django's admin and in
      automatically-generated forms.
Here are all available field types:
``AutoField``
~~~~~~~~~~~~~
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
`Automatic primary key fields`_.
``BooleanField``
~~~~~~~~~~~~~~~~
A true/false field.
The admin represents this as a checkbox.
``CharField``
~~~~~~~~~~~~~
A string field, for small- to large-sized strings.
For large amounts of text, use ``TextField``.
The admin represents this as an ``_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 }}``.
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``.
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
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.
.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
**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.
``FilePathField``
~~~~~~~~~~~~~~~~~
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**:
    ======================  ===================================================
    Argument                Description
    ======================  ===================================================
    ``path``                Required. The absolute filesystem path to a
                            directory from which this ``FilePathField`` should
                            get its choices. Example: ``"/home/images"``.
    ``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``.
    ``recursive``           Optional. Either ``True`` or ``False``. Default is
                            ``False``. Specifies whether all subdirectories of
                            ``path`` should be included.
    ======================  ===================================================
Of course, these arguments can be used together.
The one potential gotcha is that ``match`` applies to the base filename,
not the full path. So, this example::
    FilePathField(path="/home/images", match="foo.*", recursive=True)
...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``).
**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.
``FloatField``
~~~~~~~~~~~~~~
**Changed in Django development version**
A floating-point number represented in Python by a ``float`` instance.
The admin represents this as an ```` box with "Unknown", "Yes" and "No" choices.
``PhoneNumberField``
~~~~~~~~~~~~~~~~~~~~
A ``CharField`` that checks that the value is a valid U.S.A.-style phone
number (in the format ``XXX-XXX-XXXX``).
``PositiveIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~
Like an ``IntegerField``, but must be positive.
``PositiveSmallIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Like a ``PositiveIntegerField``, but only allows values under a certain
(database-dependent) point.
``SlugField``
~~~~~~~~~~~~~
"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.
Like a CharField, you can specify ``max_length``. If ``max_length`` is
not specified, Django will use a default length of 50.
Implies ``db_index=True``.
``SmallIntegerField``
~~~~~~~~~~~~~~~~~~~~~
Like an ``IntegerField``, but only allows values under a certain
(database-dependent) point.
``TextField``
~~~~~~~~~~~~~
A large text field.
The admin represents this as a ``