Model Definition Reference

Chapter 4 explains the basics of defining models, and we use them throughout the rest of the book. There is, however, a huge range of model options available not covered elsewhere. This appendix explains each possible model definition option.

Fields

The most important part of a model – and the only required part of a model – is the list of database fields it defines.

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' has two underscores!
             foo__bar = models.IntegerField() 
    

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 forms and admin site, if you care to use it (e.g., <input type="text">, <select>).
  • The minimal validation requirements, which are used in Django’s admin interface and by forms.

Each field class can be passed a list of option arguments, for example when we were building the book model in Chapter 4, our num_pages field looked like this:

num_pages = models.IntegerField(blank=True, null=True)

In this case, we are setting the blank and null options for the field class. Table A-2 lists all the field options in Django.

A number of fields also define additional options specific to that class, for example the CharField class has a required option max_length which defaults to None.
For example:

    title = models.CharField(max_length=100)

In this case we are setting the max_length field option to 100 to limit our book titles to 100 characters.

A complete list of field classes is in Table A-1, sorted alphabetically.

Table A-1: Django Model Field Reference

Field Default Widget Description
AutoField N/A An IntegerField that automatically increments according to available IDs.
BigIntegerField NumberInput A 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807
BinaryField N/A A field to store raw binary data. It only supports bytes assignment. Be aware that this field has limited functionality.
BooleanField CheckboxInput A true/false field. If you need to accept null values then use NullBooleanField instead.
CharField TextInput A string field, for small- to large-sized strings. For large amounts of text, use TextField.CharField has one extra required argument: max_length. The maximum length (in characters) of the field.
DateField DateInput A date, represented in Python by a datetime.date instance. Has two extra, optional arguments: auto_now which automatically set the field to now every time the object is saved, and auto_now_add which automatically set the field to now when the object is first created.
DateTimeField DateTimeInput A date and time, represented in Python by a datetime.datetime instance. Takes the same extra arguments as DateField.
DecimalField TextInput A fixed-precision decimal number, represented in Python by a Decimal instance. Has two required arguments: max_digits and decimal_places.
DurationField TextInput A field for storing periods of time – modeled in Python by timedelta.
EmailField TextInput A CharField that uses EmailValidator to validate the input. max_length defaults to 254.
FileField ClearableFileInput A file upload field. For more information on FileField, see the next section.
FilePathField Select A CharField whose choices are limited to the filenames in a certain directory on the filesystem.
FloatField NumberInput A floating-point number represented in Python by a float instance. Note when field.localize is False, the default widget is TextInput
ImageField ClearableFileInput Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. Additional height and width attributes. Requires the Pillow[70] library.
IntegerField NumberInput An integer. Values from -2147483648 to 2147483647 are safe in all databases supported by Django.
GenericIPAddressField TextInput An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or 2a02:42fe::4).
NullBooleanField NullBooleanSelect Like a BooleanField, but allows NULL as one of the options.
PositiveIntegerField NumberInput An integer . Values from 0 to 2147483647 are safe in all databases supported by Django.
SlugField TextInput Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens.
SmallIntegerField NumberInput Like an IntegerField, but only allows values under a certain point. Values from -32768 to 32767 are safe in all databases supported by Django.
TextField Textarea A large text field. If you specify a max_length attribute, it will be reflected in the Textarea widget of the auto-generated form field.
TimeField TextInput A time, represented in Python by a datetime.time instance.
URLField URLInput A CharField for a URL. Optional max_length argument.
UUIDField TextInput A field for storing universally unique identifiers. Uses Python’s UUID class.

FileField Notes

The primary_key and unique arguments are not supported, and will raise a TypeError if used.

Has two optional arguments:

  1. FileField.upload_to
  2. FileField.storage
FileField.upload_to

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:

  • 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.
FileField.storage

A storage object, which handles the storage and retrieval of your files. The default form widget for this field is a ClearableFileInput. 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, defining the upload_to option to specify a subdirectory of MEDIA_ROOT to use for uploaded 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 convenient url attribute 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 }}.

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. FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.

FileField and FieldFile

When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file. In addition to the functionality inherited from django.core.files.File, this class has several attributes and methods that can be used to interact with file data:

FieldFile.url

A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.

FieldFile.open(mode=’rb’)

Behaves like the standard Python open() method and opens the file associated with this instance in the mode specified by mode.

FieldFile.close()

Behaves like the standard Python file.close() method and closes the file associated with this instance.

FieldFile.save(name, content, save=True)

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 model instance is saved after the file associated with this field 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:

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

Or you can construct one from a Python string like this:

from django.core.files.base import ContentFile
myfile = ContentFile("hello world")
FieldFile.delete(save=True)

Deletes the file associated with this instance and clears all attributes on the field. 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 model instance is saved after the file associated with this field has been deleted. Defaults to True.

Note that when a model is deleted, related files are not deleted. If you need to clean up 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).

Universal Field Options

Table A-2 lists all the optional field arguments in Django. They are available to all field types.

Table A-2: Django Universal Field Options

Option Description
null If True, Django will store empty values as NULL in the database. Default is False. Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms. If you want to accept null values with BooleanField, use NullBooleanField instead.
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.
choices An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.
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, a database index will be created for this field.
db_tablespace 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.
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. 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.
editable If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
error_messages The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. Error message keys include null, blank, invalid, invalid_choice, unique, and unique_for_date.
help_text Extra help text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. Note that this value is not HTML-escaped in automatically-generated forms. This lets you include HTML in help_text if you so desire.
primary_key If True, this field is the primary key for the model. 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. The primary key field is read-only.
unique If True, this field must be unique throughout the table. This is enforced at the database level and by model validation. This option is valid on all field types except ManyToManyField, OneToOneField, and FileField.
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 by Model.validate_unique() during model validation 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, but requires the field to be unique with respect to the year.
verbose_name A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validators A list of validators to run for this field.

Field Attribute Reference

Every Field instance contains several attributes that allow introspecting its behavior. Use these attributes instead of isinstance checks when you need to write code that depends on a field’s functionality. These attributes can be used together with the Model._meta API to narrow down a search for specific field types. Custom model fields should implement these flags.

Attributes for Fields

Field.auto_created

Boolean flag that indicates if the field was automatically created, such as the OneToOneField used by model inheritance.

Field.concrete

Boolean flag that indicates if the field has a database column associated with it.

Field.hidden

Boolean flag that indicates if a field is used to back another non-hidden field’s functionality (e.g. the content_type and object_id fields that make up a GenericForeignKey). The hidden flag is used to distinguish what constitutes the public subset of fields on the model from all the fields on the model.

Field.is_relation

Boolean flag that indicates if a field contains references to one or more other models for its functionality (e.g. ForeignKey, ManyToManyField, OneToOneField, etc.).

Field.model

Returns the model on which the field is defined. If a field is defined on a superclass of a model, model will refer to the superclass, not the class of the instance.

Attributes for Fields with Relations

These attributes are used to query for the cardinality and other details of a relation. These attribute are present on all fields; however, they will only have meaningful values if the field is a relation type (Field.is_relation=True).

Field.many_to_many

Boolean flag that is True if the field has a many-to-many relation; False otherwise. The only field included with Django where this is True is ManyToManyField.

Field.many_to_one

Boolean flag that is True if the field has a many-to-one relation, such as a ForeignKey; False otherwise.

Field.one_to_many

Boolean flag that is True if the field has a one-to-many relation, such as a GenericRelation or the reverse of a ForeignKey; False otherwise.

Field.one_to_one

Boolean flag that is True if the field has a one-to-one relation, such as a OneToOneField; False otherwise.

Field.related_model

Points to the model the field relates to.
For example, Author in ForeignKey(Author). If a field has a generic relation (such as a GenericForeignKey or a GenericRelation) then related_model will be None.

Relationships

Django also defines a set of fields that represent relations.

ForeignKey

A many-to-one relationship. Requires a positional argument: the class to which the model is related. 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:

from django.db import models

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...

class Manufacturer(models.Model):
    # ...
    pass To refer to models defined in another application, you can explicitly specif\
y a model with the full application label. For example, if the `Manufacturer` model a\
bove is defined in another application called `production`, you'd need to use:

class Car(models.Model):
    manufacturer = models.ForeignKey('production.Manufacturer')

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.

Database Representation

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.

Arguments

ForeignKey accepts an extra set of arguments – all optional – that define the details of how the relation works.

limit_choices_to

Sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or object can be used. For example:

staff_member = models.ForeignKey(User, limit_choices_to={'is_staff': True})

causes the corresponding field on the ModelForm to list only Users that have is_staff=True. This may be helpful in the Django admin. The callable form can be helpful, for instance, when used in conjunction with the Python datetime module to limit selections by date range. For example:

def limit_pub_date_choices():
    return {'pub_date__lte': datetime.date.utcnow()}

limit_choices_to = limit_pub_date_choices 

If limit_choices_to is or returns a Q object, which is useful for complex queries, 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.

related_name

The name to use for the relation from the related object back to this one. It’s also the default value for related_query_name (the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available. If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model:

user = models.ForeignKey(User, related_name='+')
related_query_name

The name to use for the reverse filter name from the target model. Defaults to the value of related_name if it is set, otherwise it defaults to the name of the model:

# Declare the ForeignKey with related_query_name
class Tag(models.Model):
    article = models.ForeignKey(Article, related_name="tags",   
      related_query_name="tag")
    name = models.CharField(max_length=255)

# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")
to_field

The field on the related object that the relation is to. By default, Django uses the primary key of the related object.

db_constraint

Controls whether or not a constraint should be created in the database for this foreign key. The default is True, and that’s almost certainly what you want; setting this to False can be very bad for data integrity. That said, here are some scenarios where you might want to do this:

  • You have legacy data that is not valid.
  • You’re sharding your database.

If this is set to False, accessing a related object that doesn’t exist will raise its DoesNotExist exception.

on_delete

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE 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:

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

The possible values for on_delete are found in django.db.models:

  • CASCADE: Cascade deletes; the default.
  • PROTECT: Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.
  • SET_NULL: Set the ForeignKey null; this is only possible if null is True.
  • SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.
swappable

Controls the migration framework’s reaction if this ForeignKey is pointing at a swappable model. If it is True – the default – then if the ForeignKey is pointing at a model which matches the current value of settings.AUTH_USER_MODEL (or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.

You only want to override this to be False if you are sure your model should always point towards the swapped-in model – for example, if it is a profile model designed specifically for your custom user model. Setting it to False does not mean you can reference a swappable model even if it is swapped out – False just means that the migrations made with this ForeignKey will always reference the exact model you specify (so it will fail hard if the user tries to run with a User model you don’t support, for example). If in doubt, leave it to its default of True.

ManyToManyField

A many-to-many relationship. Requires a positional argument: the class to which the model is related, which works exactly the same as it does for ForeignKey, including recursive and lazy relationships. Related objects can be added, removed, or created with the field’s RelatedManager.

Database Representation

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 name of the table for 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.

Arguments

ManyToManyField accepts an extra set of arguments – all optional – that control how the relationship functions.

related_name

Same as ForeignKey.related_name.

related_query_name

Same as ForeignKey.related_query_name.

limit_choices_to

Same as ForeignKey.limit_choices_to. limit_choices_to has no effect when used on a ManyToManyField with a custom intermediate table specified using the through parameter.

symmetrical

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

from django.db import models

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

through

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.

The most common use for this option is when you want to associate extra data with a many-to-many relationship. If you don’t specify an explicit through model, there is still an implicit through model class you can use to directly access the table created to hold the association. It has three fields:

  • id: the primary key of the relation.
  • <containing_model>_id: the id of the model that declares the ManyToManyField.
  • <other_model>_id: the id of the model that the ManyToManyField points to.

This class can be used to query associated records for a given model instance like a normal model.

through_fields

Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically.

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 table for the model defining the relationship and the name of the field itself.

db_constraint

Controls whether or not constraints should be created in the database for the foreign keys in the intermediary table. The default is True, and that’s almost certainly what you want; setting this to False
can be very bad for data integrity.

That said, here are some scenarios where you might want to do this:

  • You have legacy data that is not valid.
  • You’re sharding your database.

It is an error to pass both db_constraint and through.

swappable

Controls the migration framework’s reaction if this ManyToManyField is pointing at a swappable model. If it is True – the default – then if the ManyToManyField is pointing at a model which matches the current value of settings.AUTH_USER_MODEL (or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.

You only want to override this to be False if you are sure your model should always point towards the swapped-in model – for example, if it is a profile model designed specifically for your custom user model. If in doubt, leave it to its default of True. ManyToManyField does not support validators. null
has no effect since there is no way to require a relationship at the database level.

OneToOneField

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. If you do not specify the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value. With the following example:

from django.conf import settings
from django.db import models

class MySpecialUser(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    supervisor = models.OneToOneField(settings.AUTH_USER_MODEL,   
      related_name='supervisor_of')

your resulting User model will have the following attributes:

>>> user = User.objects.get(pk=1)
>>> hasattr(user, 'myspecialuser')
True
>>> hasattr(user, 'supervisor_of')
True 

A DoesNotExist exception is raised when accessing the reverse relationship if an entry in the related table doesn’t exist. For example, if a user doesn’t have a supervisor designated by MySpecialUser:

>>> user.supervisor_of
Traceback (most recent call last):
    ...
DoesNotExist: User matching query does not exist.

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. See “one-to-one relationships” in the next chapter for usage examples of OneToOneField.

Model Metadata Options

Table A-3 is a complete list of model meta options you can give your model in its internal class Meta. For more detail on each meta option as well as examples, see the Django documentation.

Table A-3: Model Metadata Options

Option Notes
abstract If abstract = True, this model will be an abstract base class.
app_label If a model is defined outside of an application in INSTALLED_APPS, it must declare which app it belongs to.
db_table The name of the database table to use for the model.
db_tablespace The name of the database tablespace to use for this model. The default is the project’s DEFAULT_TABLESPACE setting, if set. If the backend doesn’t support tablespaces, this option is ignored.
default_related_name The name that will be used by default for the relation from a related object back to this one. The default is <model_name>_set.
get_latest_by The name of an orderable field in the model, typically a DateField, DateTimeField, or IntegerField.
managed Defaults to True, meaning Django will create the appropriate database tables in migrate or as part of migrations and remove them as part of a flush management command.
order_with_respect_to Marks this object as orderable with respect to the given field.
ordering The default ordering for the object, for use when obtaining lists of objects.
permissions Extra permissions to enter into the permissions table when creating this object.
default_permissions Defaults to (‘add’, ‘change’, ‘delete’).
proxy If proxy = True, a model which subclasses another model will be treated as a proxy model.
select_on_save Determines if Django will use the pre-1.6 django.db.models.Model.save() algorithm.
unique_together Sets of field names that, taken together, must be unique.
index_together Sets of field names that, taken together, are indexed.
verbose_name A human-readable name for the object, singular.
verbose_name_plural The plural name for the object.