Technically, these models are defined in django.db.models.fields, but
for convenience they’re imported into django.db.models; the standard
convention is to use fromdjango.dbimportmodels and refer to fields as
models.<Foo>Field.

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).

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 have the empty string as a possible
value, and the value NULL will be stored to denote the empty string.

Note that this is different than null. null is
purely database-related, whereas blank is validation-related. If
a field has blank=True, form validation will allow entry of an empty value.
If a field has blank=False, the field will be required.

The first element in each tuple is the name to apply to the group. The
second element is an iterable of 2-tuples, with each 2-tuple containing
a value and a human-readable name for an option. Grouped options may be
combined with ungrouped options within a single list (such as the
unknown option in this example).

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.

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 for indexes, this option is ignored.

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.

The default cannot be a mutable object (model instance, list, set, etc.), as a
reference to the same instance of that object would be used as the default
value in all new model instances. Instead, wrap the desired default in a
callable. For example, if you had a custom JSONField and wanted to specify
a dictionary as the default, use a lambda as follows:

If you don’t specify primary_key=True for any field in your model, Django
will automatically add an AutoField to hold the primary key, so you
don’t need to set primary_key=True on any of your fields unless you want to
override the default primary-key behavior. For more, see
Automatic primary key fields.

This is enforced at the database level and by model validation. 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.

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.

Changed in Django 1.2: In previous versions of Django when running under MySQL BooleanFields
would return their data as ints, instead of true bools. See the
release notes for a complete description of the change.

The maximum length (in characters) of the field. The max_length is enforced
at the database level and in Django’s validation.

Note

If you are writing an application that must be portable to multiple
database backends, you should be aware that there are restrictions on
max_length for some backends. Refer to the database backend
notes for details.

MySQL users

If you are using this field with MySQLdb 1.2.2 and the utf8_bin
collation (which is not the default), there are some issues to be aware
of. Refer to the MySQL database notes for
details.

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.

A local filesystem path that will be appended to your MEDIA_ROOT
setting to determine the value of the url
attribute.

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).

This may also be a callable, such as a function, which will be called to
obtain the upload path, including the filename. This 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.

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.

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.

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 url function provided by
Django. For example, if your ImageField is called mug_shot,
you can get the absolute path to your image in a template with
{{object.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 wanted to retrieve the uploaded file’s on-disk filename, or the file’s
size, you could use the name and
size attributes respectively; for more
information on the available attributes and methods, see the
File class reference and the Managing files
topic guide.

Note

The file is saved as part of saving the model in the database, so the actual
file name used on disk cannot be relied on until after the model has been
saved.

The uploaded file’s relative URL can be obtained using the
url attribute. Internally,
this calls the url() method of the
underlying Storage class.

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.

Also note that even an uploaded HTML file, since it can be executed by the
browser (though not by the server), can pose security threats that are
equivalent to XSS or CSRF attacks.

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.

This method takes a filename and file contents and passes them to the storage
class for the field, then associates the stored file with the model field.
If you want to manually associate file data with FileField
instances on your model, the save() method is used to persist that file
data.

Takes two required arguments: name which is the name of the file, and
content which is an object containing the file’s contents. The
optional save argument controls whether or not the instance is
saved after the file has been altered. Defaults to True.

Note that the content argument should be an instance of
django.core.files.File, not Python’s built-in file object.
You can construct a File from an existing
Python file object like this:

fromdjango.core.filesimportFile# Open an existing file using Python's built-in open()f=open('/tmp/hello.world')myfile=File(f)

Deletes the file associated with this instance and clears all attributes on
the field. Note: This method will close the file if it happens to be open when
delete() is called.

The optional save argument controls whether or not the instance is saved
after the file has been deleted. Defaults to True.

Note that when a model is deleted, related files are not deleted. If you need
to cleanup orphaned files, you’ll need to handle it yourself (for instance,
with a custom management command that can be run manually or scheduled to run
periodically via e.g. cron).

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.

The FloatField class is sometimes mixed up with the
DecimalField class. Although they both represent real numbers, they
represent those numbers differently. FloatField uses Python’s float
type internally, while DecimalField uses Python’s Decimal type. For
information on the difference between the two, see Python’s documentation
for the decimal module.

An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or
2a02:42fe::4). The default form widget for this field is a
TextInput.

The IPv6 address normalization follows RFC 4291 section 2.2,
including using the IPv4 format suggested in paragraph 3 of that section, like
::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to
2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters
are converted to lowercase.

To refer to models defined in another application, you can explicitly specify
a model with the full application label. For example, if the Manufacturer
model above is defined in another application called production, you’d
need to use:

This sort of reference can be useful when resolving circular import
dependencies between two applications.

A database index is automatically created on the ForeignKey. You can
disable this by setting db_index to False. You may want to
avoid the overhead of an index if you are creating a foreign key for
consistency rather than joins, or if you will be creating an alternative index
like a partial or multiple column index.

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) 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.

A dictionary of lookup arguments and values (see Making queries)
that limit the available admin or ModelForm 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 for more complex queries. However,
if limit_choices_to is a Q object then it
will only have an effect on the choices available in the admin when the
field is not listed in raw_id_fields in the ModelAdmin for the model.

When an object referenced by a ForeignKey is deleted, Django by
default emulates the behavior of the SQL constraint ONDELETECASCADE
and also deletes the object containing the ForeignKey. This behavior
can be overridden by specifying the on_delete argument. For
example, if you have a nullable ForeignKey and you want it to be
set null when the referenced object is deleted:

SET(): Set the ForeignKey to the value
passed to SET(), or if a callable is passed in,
the result of calling it. In most cases, passing a callable will be
necessary to avoid executing queries at the time your models.py is
imported:

DO_NOTHING: Take no action. If your database
backend enforces referential integrity, this will cause an
IntegrityError unless you manually add a SQL ONDELETE constraint to the database field (perhaps using
initial sql).

A many-to-many relationship. Requires a positional argument: the class to which
the model is related. This works exactly the same as it does for
ForeignKey, including all the options regarding recursive and lazy relationships.

Related objects can be added, removed, or created with the field’s
RelatedManager.

Behind the scenes, Django creates an intermediary join table to
represent the many-to-many relationship. By default, this table name
is generated using the name of the many-to-many field and the model
that contains it. Since some databases don’t support table names above
a certain length, these table names will be automatically truncated to
64 characters and a uniqueness hash will be used. This means you might
see table names like author_books_9cdf4; this is perfectly normal.
You can manually provide the name of the join table using the
db_table option.

Only used in the definition of ManyToManyFields on self. Consider the
following model:

classPerson(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 many-to-many relationships with self, set
symmetrical to False. This will force Django to
add the descriptor for the reverse relationship, allowing
ManyToManyField relationships to be non-symmetrical.

Django will automatically generate a table to manage many-to-many
relationships. However, if you want to manually specify the intermediary
table, you can use the through option to specify
the Django model that represents the intermediate table that you want to
use.

A one-to-one relationship. Conceptually, this is similar to a
ForeignKey with unique=True, but the
“reverse” side of the relation will directly return a single object.

This is most useful as the primary key of a model which “extends”
another model in some way; Multi-table inheritance is
implemented by adding an implicit one-to-one relation from the child
model to the parent model, for example.

One positional argument is required: the class to which the model will be
related. This works exactly the same as it does for ForeignKey,
including all the options regarding recursive
and lazy relationships.

Additionally, OneToOneField accepts all of the extra arguments
accepted by ForeignKey, plus one extra argument:

When True and used in a model which inherits from another
(concrete) model, indicates that this field should be used as the
link back to the parent class, rather than the extra
OneToOneField which would normally be implicitly created by
subclassing.