Django model fields options
In Django, a model represents a database table, and its fields define the columns of the table. Each field has a type and a set of options that can be used to customize its behavior. Here are some of the most common field options and their details:
null
: This option determines whether the field can be set to NULL (i.e., have no value). The default value isFalse
, meaning that the field is required.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, null=True)
In this example, my_field
is a CharField that can be set to NULL.
2. blank
: This option determines whether the field is required to have a value. The default value is False
, meaning that the field is required.
Example
class MyModel(models.Model):
my_field = models.CharField(max_length=100, blank=True)
In this example, my_field
is a CharField that is not required to have a value.
3. default
: This option specifies the default value of the field. The default value is None
, meaning that the field has no default value.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, default='default value')
In this example, my_field
is a CharField that has a default value of 'default value'
.
4. choices
: This option specifies a list of choices for the field. The choices can be any iterable (e.g., a list, tuple, or dictionary).
Example:
class MyModel(models.Model):
COLOR_CHOICES = [
('R', 'Red'),
('G', 'Green'),
('B', 'Blue')
]
color = models.CharField(max_length=1, choices=COLOR_CHOICES)
In this example, color
is a CharField that can only be set to 'R'
, 'G'
, or 'B'
.
5. max_length
: This option specifies the maximum length of the field. It is required for CharField and TextField.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100)
In this example, my_field
is a CharField that can have a maximum length of 100 characters.
6. unique
: This option specifies whether the field must be unique.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, unique=True)
In this example, my_field
is a CharField that must have a unique value.
7. verbose_name
: This option specifies a human-readable name for the field. If not specified, Django will use the field name with underscores replaced by spaces.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, verbose_name='My custom name')
In this example, the field will be displayed as “My custom name” instead of “my_field” in forms, admin site, etc.
8. db_column
: This option specifies the name of the column in the database. If not specified, Django will use the field name.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, db_column='custom_column')
In this example, the field will be stored in a database column named “custom_column” instead of “my_field”.
9. db_index
: This option specifies whether an index should be created on the field in the database. Indexes can speed up queries, but can also slow down writes.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, db_index=True)
In this example, an index will be created on the “my_field” column in the database.
10. auto_now
: This option specifies whether the field should be automatically set to the current date and time whenever the object is saved.
Example:
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
In this example, the “created_at” field will be set to the current date and time when the object is first created, and the “updated_at” field will be set to the current date and time whenever the object is saved.
11. editable
: This option specifies whether the field can be edited in forms and the admin site. The default value is True
.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, editable=False)
In this example, the “my_field” field cannot be edited in forms or the admin site.
12. related_name
: This option specifies the name of the reverse relation from the related model back to the model with the foreign key. If not specified, Django will use the lowercased name of the model as the default value.
Example:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
In this example, the reverse relation from Author to Book will be named “books”.
13. on_delete
: This option specifies the behavior to use when the referenced object is deleted. The default value is models.CASCADE
, which deletes the objects that have a foreign key reference to the deleted object.
Example:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
In this example, when an Author is deleted, the author field of all associated Book objects will be set to NULL.
14. validators
: This option specifies a list of validator functions to use to validate the field. Validator functions should take a single argument (the field value) and raise a ValidationError
if the value is invalid.
Example:
from django.core.exceptions import ValidationError
def validate_even(value):
if value % 2 != 0:
raise ValidationError('Value must be even.')
class MyModel(models.Model):
my_field = models.IntegerField(validators=[validate_even])
In this example, the “my_field” field can only have even values.
15. upload_to
: This option specifies the directory to which uploaded files will be uploaded. If the directory does not exist, it will be created.
Example:
class MyModel(models.Model):
my_file = models.FileField(upload_to='uploads/')
In this example, uploaded files will be stored in the “uploads/” directory in the default media storage location.
16. help_text
: This option specifies a help text to display alongside the field in forms and the admin site.
Example:
class MyModel(models.Model):
my_field = models.CharField(max_length=100, help_text='Enter a short description.')
In this example, the field will display the help text “Enter a short description.” in forms and the admin site.
17. unique_for_date
, unique_for_month
, and unique_for_year
: These options specify that the field should be unique for a given date, month, or year, respectively. These options require the name of a DateField or DateTimeField in the model, which specifies the date to which the uniqueness constraint applies.
Example:
class MyModel(models.Model):
date = models.DateField()
value = models.IntegerField()
class Meta:
unique_together = ('date', 'value')
unique_for_date = ('date', 'value')
In this example, the unique_together
option specifies that the combination of date
and value
should be unique. The unique_for_date
option specifies that the value
field should be unique for each date
.
The difference between unique
and these options is that unique
applies to the entire table, while unique_for_date
, unique_for_month
, and unique_for_year
apply to a specific date range.
For example, suppose we have a model with a date
field and a value
field, and we want to ensure that each value
is unique for each day. We could use the unique_for_date
option to accomplish this. However, if we wanted to ensure that each value
is unique across all dates in the table, we would use the unique
option instead.