=============== 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. ````, ```` (a single-line input). ``CharField`` has an extra required argument, ``max_length``, the maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation. ``CommaSeparatedIntegerField`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A field of integers separated by commas. As in ``CharField``, the ``max_length`` argument is required. ``DateField`` ~~~~~~~~~~~~~ A date field. Has a few extra optional arguments: ====================== =================================================== Argument Description ====================== =================================================== ``auto_now`` Automatically set the field to now every time the object is saved. Useful for "last-modified" timestamps. Note that the current date is *always* used; it's not just a default value that you can override. ``auto_now_add`` Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is *always* used; it's not just a default value that you can override. ====================== =================================================== The admin represents this as an ```` with a JavaScript calendar, and a shortcut for "Today." The JavaScript calendar will always start the week on a Sunday. ``DateTimeField`` ~~~~~~~~~~~~~~~~~ A date and time field. Takes the same extra options as ``DateField``. The admin represents this as two ```` fields, with JavaScript shortcuts. ``DecimalField`` ~~~~~~~~~~~~~~~~ **New in Django development version** A fixed-precision decimal number, represented in Python by a ``Decimal`` instance. Has two **required** arguments: ====================== =================================================== Argument Description ====================== =================================================== ``max_digits`` The maximum number of digits allowed in the number. ``decimal_places`` The number of decimal places to store with the number. ====================== =================================================== For example, to store numbers up to 999 with a resolution of 2 decimal places, you'd use:: models.DecimalField(..., max_digits=5, decimal_places=2) And to store numbers up to approximately one billion with a resolution of 10 decimal places:: models.DecimalField(..., max_digits=19, decimal_places=10) The admin represents this as an ```` (a single-line input). ``EmailField`` ~~~~~~~~~~~~~~ A ``CharField`` that checks that the value is a valid e-mail address. In Django 0.96, this doesn't accept ``max_length``; its ``max_length`` is automatically set to 75. In the Django development version, ``max_length`` is set to 75 by default, but you can specify it to override default behavior. ``FileField`` ~~~~~~~~~~~~~ A file-upload field. Has two special arguments, of which the first is **required**: ====================== =================================================== Argument Description ====================== =================================================== ``upload_to`` Required. A filesystem-style path that will be prepended to the filename before being committed to the final storage destination. **New in Django development version** This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. See below for details. ``storage`` **New in Django development version** Optional. A storage object, which handles the storage and retrieval of your files. See `managing files`_ for details on how to provide this object. ====================== =================================================== .. _managing files: ../files/ The ``upload_to`` 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). **New in Django development version** If a callable is provided for the ``upload_to`` argument, that callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are: ====================== =================================================== Argument Description ====================== =================================================== ``instance`` An instance of the model where the ``FileField`` is defined. More specifically, this is the particular instance where the current file is being attached. **Note**: In most cases, this object will not have been saved to the database yet, so if it uses the default ``AutoField``, *it might not yet have a value for its primary key field*. ``filename`` The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path. ====================== =================================================== The admin represents this field as an ```` (a file-upload widget). Using a ``FileField`` or an ``ImageField`` (see below) in a model without a specified storage system takes a few steps: 1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the 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. 2. Add the ``FileField`` or ``ImageField`` to your model, making sure to define the ``upload_to`` option to tell Django to which subdirectory of ``MEDIA_ROOT`` it should upload files. 3. All that will be stored in your database is a path to the file (relative to ``MEDIA_ROOT``). You'll most likely want to use the convenience ``get__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``. Information about the uploaded ``File`` object, such as its on-disk filename, its size, or its URL, is available via attributes on the object itself. See the `managing files`__ documentation for more information about ``File`` objects. __ ../files/ 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 ```` (a single-line input). **NOTE:** The semantics of ``FloatField`` have changed in the Django development version. See the `Django 0.96 documentation`_ for the old behavior. .. _Django 0.96 documentation: http://www.djangoproject.com/documentation/0.96/model-api/#floatfield ``ImageField`` ~~~~~~~~~~~~~~ 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. In addition to the `standard attributes and methods`_ that are available for ``FileField``, an ``ImageField`` also has ``width`` and ``height`` attributes. Requires the `Python Imaging Library`_. **New in development version:** By default, ``ImageField`` instances are created as ``varchar(100)`` columns in your database. As with other fields, you can change the maximum length using the ``max_length`` argument. .. _standard attributes and methods: ../files/#file-attributes-and-methods .. _Python Imaging Library: http://www.pythonware.com/products/pil/ ``IntegerField`` ~~~~~~~~~~~~~~~~ An integer. The admin represents this as an ```` (a single-line input). ``IPAddressField`` ~~~~~~~~~~~~~~~~~~ An IP address, in string format (e.g. "192.0.2.30"). The admin represents this as an ```` (a single-line input). ``NullBooleanField`` ~~~~~~~~~~~~~~~~~~~~ Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this instead of a ``BooleanField`` with ``null=True``. The admin represents this as a ``