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.
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. <input type="text">, <select>).
- The minimal validation requirements, used in Django’s admin and in
manipulators.
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 <input type="text"> (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.
Django veterans: Note that the argument is now called max_length to
provide consistency throughout Django. There is full legacy support for
the old maxlength argument, but max_length is preferred.
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 <input type="text"> 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 <input type="text"> 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 <input type="text"> (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 one required argument:
| Argument |
Description |
| upload_to |
A local filesystem path that will be appended to
your MEDIA_ROOT setting to determine the
output of the get_<fieldname>_url() helper
function. |
This path may contain strftime formatting, which will be replaced by the
date/time of the file upload (so that uploaded files don’t fill up the given
directory).
The admin represents this field as an <input type="file"> (a file-upload
widget).
Using a FileField or an ImageField (see below) in a model takes a few
steps:
- 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.
- 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.
- 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_<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 }}.
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.
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.
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 <input type="text"> (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.
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 special get_FOO_* methods that are available for
FileField, an ImageField also has get_FOO_height() and
get_FOO_width() methods. These are documented elsewhere.
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.
IntegerField
An integer.
The admin represents this as an <input type="text"> (a single-line input).
IPAddressField
An IP address, in string format (e.g. “192.0.2.30”).
The admin represents this as an <input type="text"> (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 <select> 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.
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:
models.SlugField(prepopulate_from=("pre_name", "name"))
prepopulate_from doesn’t accept DateTimeFields, ForeignKeys nor
ManyToManyFields.
The admin represents SlugField as an <input type="text"> (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 <textarea> (a multi-line input).
TimeField
A time. Accepts the same auto-population options as DateField and
DateTimeField.
The admin represents this as an <input type="text"> with some
JavaScript shortcuts.
URLField
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).
The admin represents this as an <input type="text"> (a single-line input).
URLField takes an optional argument, max_length, the maximum length (in
characters) of the field. The maximum length is enforced at the database level and
in Django’s validation. If you don’t specify max_length, a default of 200
is used.
USStateField
A two-letter U.S. state abbreviation.
The admin represents this as an <input type="text"> (a single-line input).
XMLField
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.
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. Only use null=True for non-string fields such as integers,
booleans and dates. For both types of fields, you will also need to set
blank=True if you wish to permit empty values in forms, as the null
parameter only affects database storage (see blank, below).
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.
Note
When using the Oracle database backend, the null=True option will
be coerced for string-based fields that can blank, and the value
NULL will be stored to denote the empty string.
blank
If True, the field is allowed to be blank. Default is False.
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
An iterable (e.g., a list or tuple) 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.
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(max_length=1, choices=GENDER_CHOICES)
or outside your model class altogether:
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Foo(models.Model):
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
For each model field that has choices set, Django will add a method to
retrieve the human-readable name for the field’s current value. See
get_FOO_display in the database API documentation.
Finally, note that choices can be any iterable object — not necessarily a
list or tuple. This lets you construct choices dynamically. But if you find
yourself hacking choices to be dynamic, you’re probably better off using
a proper database table with a ForeignKey. choices is meant for static
data that doesn’t change much, if ever.
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.
Please note that each field marked “core” is treated as a required field by the
Django admin site. Essentially, this means you should put core=True on all
required fields in your related object that is being edited inline.
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.
db_tablespace
New in Django development version
The name of the database tablespace to use for this field’s index, if
this field is indexed. The default is the project’s
DEFAULT_INDEX_TABLESPACE setting, if set, or the db_tablespace
of the model, if any. If the backend doesn’t support tablespaces, this
option is ignored.
default
The default value for the field. This can be a value or a callable object. If
callable it will be called every time a new object is created.
editable
If False, the field will not be editable in the admin or via form
processing using the object’s AddManipulator or ChangeManipulator
classes. 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.
Note that this value is not HTML-escaped when it’s displayed in the admin
interface. This lets you include HTML in help_text if you so desire. For
example:
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
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 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. If
you try to save a model with a duplicate value in a unique field, a
django.db.IntegrityError will be raised by the model’s save() method.
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.
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", max_length=30)
In this example, the verbose name is "first name":
first_name = models.CharField(max_length=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.
Relationships
Clearly, the power of relational databases lies in relating tables to each
other. Django offers ways to define the three most common types of database
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.
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:
class Manufacturer(models.Model):
# ...
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
# ...
To create a recursive relationship — an object that has a many-to-one
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:
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
Note, however, that this only refers to models in the same models.py file — you
cannot use a string to reference a model defined in another application or
imported from elsewhere.
New in Django development version: To refer to models defined in another
application, you must instead explicitly specify the application label. For
example, if the Manufacturer model above is defined in another application
called production, you’d need to use:
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
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
should never have to deal with the database column name, unless you write
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)
# ...
See the Many-to-one relationship model example for a full example.
ForeignKey fields take a number of extra arguments for defining how the
relationship should work. All are optional:
| Argument |
Description |
| edit_inline |
If True, this related object is edited
“inline” on the related object’s page. This means
that the object will not have its own admin
interface. Use either models.TABULAR or models.STACKED,
which, respectively, designate whether the inline-editable
objects are displayed as a table or as a “stack” of
fieldsets. |
| limit_choices_to |
A dictionary of lookup arguments and values (see
the Database API reference) that limit the
available admin choices for this object. Use this
with functions from the Python datetime module
to limit choices of objects by date. For example:
limit_choices_to = {'pub_date__lte': datetime.now}
only allows the choice of related objects with a
pub_date before the current date/time to be
chosen.
Instead of a dictionary this can also be a Q object
(an object with a get_sql() method) for more complex
queries.
Not compatible with edit_inline.
|
| max_num_in_admin |
For inline-edited objects, this is the maximum
number of related objects to display in the admin.
Thus, if a pizza could only have up to 10
toppings, max_num_in_admin=10 would ensure
that a user never enters more than 10 toppings.
Note that this doesn’t ensure more than 10 related
toppings ever get created. It simply controls the
admin interface; it doesn’t enforce things at the
Python API level or database level.
|
| min_num_in_admin |
The minimum number of related objects displayed in
the admin. Normally, at the creation stage,
num_in_admin inline objects are shown, and at
the edit stage num_extra_on_change blank
objects are shown in addition to all pre-existing
related objects. However, no fewer than
min_num_in_admin related objects will ever be
displayed. |
| num_extra_on_change |
The number of extra blank related-object fields to
show at the change stage. |
| num_in_admin |
The default number of inline objects to display
on the object page at the add stage. |
| raw_id_admin |
Only display a field for the integer to be entered
instead of a drop-down menu. This is useful when
related to an object type that will have too many
rows to make a select box practical.
Not used with edit_inline.
|
| related_name |
The name to use for the relation from the related
object back to this one. See the
related objects documentation for a full
explanation and example.
If using this in an abstract base class, be
sure to read the extra notes in that section
about related_name.
|
| to_field |
The field on the related object that the relation
is to. By default, Django uses the primary key of
the related object. |
Many-to-many relationships
To define a many-to-many relationship, use ManyToManyField. You use it just
like any other Field type: by including it as a class attribute of your
model.
ManyToManyField requires a positional argument: the class to which the
model is related.
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:
class Topping(models.Model):
# ...
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
As with ForeignKey, a relationship to self can be defined by using the
string 'self' instead of the model name, and you can refer to as-yet
undefined models by using a string containing the model name. However, you
can only use strings to refer to models in the same models.py file — you
cannot use a string to reference a model in a different application, or to
reference a model that has been imported from elsewhere.
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.
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
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.
See the Many-to-many relationship model example for a full example.
ManyToManyField objects take a number of extra arguments for defining how
the relationship should work. All are optional:
| Argument |
Description |
| related_name |
See the description under ForeignKey above. |
| 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
models.HORIZONTAL or models.VERTICAL (i.e.
should the interface be stacked horizontally or
vertically). |
| limit_choices_to |
See the description under ForeignKey above. |
| 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
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.
|
| db_table |
The name of the table to create for storing the many-to-many
data. If this is not provided, Django will assume a default
name based upon the names of the two tables being joined. |
One-to-one relationships
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.
This is most useful on the primary key of an object when that object “extends”
another object in some way.
OneToOneField requires a positional argument: the class to which the
model is related.
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).
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.
Finally, OneToOneField takes the following extra option:
| Argument |
Description |
| parent_link |
When True and used in a model inherited from
another model, indicates that this field should
be used as the link from the child back to the
parent. See Model inheritance for more
details.
New in Django development version
|
New in Django development version: OneToOneField classes used to
automatically become the primary key on a model. This is no longer true,
although you can manually pass in the primary_key attribute if you like.
Thus, it’s now possible to have multiple fields of type OneToOneField on a
single model.
See the One-to-one relationship model example for a full example.