Django Models – Field Options
There are options you can add in each field. The field options give additional rules for the field. Different from the field type, the field option is written in snake_case.
1. Data validation related options
blank
The field is allowed to be blank if blank=True. If you don't set this option for the field, you cannot leave the field blank when you make an input for it.
unique
The field value must be unique in the table if unique=True. If you don't set this option for the field, you can put the same value in different records.
validators
Using this field, you can add a custom validation. To make the custom validation, you need to create validation rules with a function or class. Use the name of the function or class as a value of the option (e.g., validators=[function_name]
).
2. Data input-related options
choices
You can alter the field input to choices from a defined list using this option. Usually, the field with this option will be displayed in a drop-down list format in browsers when you deploy the app.
default
Using this option, you can set a default value for the field that is used when a new record object is created.
3. Data display-related options
help_text
Using this option, you can set help text that is shown beside the input form of the field when you deploy the app.
verbose_name
Using this option, you can customize the field name displayed in browsers when you deploy the app. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
4. Data handling related options
primary_key
When you create a model, Django automatically adds an id field to each model, which is used as the primary key for the model. Using this option, you can change the primary key to the field with this option.
db_column
Django uses a field name for the column name in the database table. Using this option, you can customize the column name.