=============== 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.core.meta.Model``. * Each attribute of the model represents a database field. * Model metadata (non-field information) goes in an inner class named ``META``. A companion to this document is the `official repository of model examples`_. .. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/ Field objects ============= The most important part of a model is the list of database fields it defines. Fields are defined by class attributes. Each class attribute in a model, aside from the optional inner ``class META``, should be an instance of a ``meta.Field`` subclass. In this example, there are two fields, ``first_name`` and ``last_name`` :: class Person(meta.Model): first_name = meta.CharField(maxlength=30) last_name = meta.CharField(maxlength=30) Django will use ``first_name`` and ``last_name`` as the database column names. Each field type, except for ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField``, takes an optional first positional argument -- a human-readable name. If the human-readable name isn't given, Django will use the machine-readable name, converting underscores to spaces. Example:: first_name = meta.CharField("Person's first name", maxlength=30) For ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField``, use the ``verbose_name`` keyword argument:: poll = meta.ForeignKey(Poll, verbose_name="the related poll") sites = meta.ManyToManyField(Site, verbose_name="list of sites") place = meta.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. General field options --------------------- The following arguments are available to all field types. All are optional. ``null`` If ``True``, Django will store empty values as ``NULL`` in the database. Default is ``False``. 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. 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``. ``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. 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. ``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. ``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 = meta.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 (``, ```` (a single-line input). ``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. ``CommaSeparatedIntegerField`` A field of integers separated by commas. As in ``CharField``, the ``maxlength`` 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. ``auto_now_add`` Automatically set the field to now when the object is first created. Useful for creation of timestamps. ====================== =================================================== The admin represents this as an ```` with a JavaScript calendar and a shortcut for "Today." ``DateTimeField`` A date and time field. Takes the same extra options as ``DateField``. The admin represents this as two ```` fields, with JavaScript shortcuts. ``EmailField`` A ``CharField`` that checks that the value is a valid e-mail address. Currently, this is a loose test. ``FileField`` A file-upload field. 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). The admin represents this as an ```` (a file-upload widget). Using a `FieldField` or an ``ImageField`` (see below) in a model 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 must 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 }}``. .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941 ``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``). ``FloatField`` A floating-point number. 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:: meta.FloatField(..., max_digits=5, decimal_places=2) And to store numbers up to one million with a resolution of 10 decimal places:: meta.FloatField(..., max_digits=19, decimal_places=10) The admin represents this as an ```` (a single-line input). ``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. Requires the `Python Imaging Library`_. .. _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 (i.e. "24.124.1.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 ```` (a single-line input). ``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 ``