Base class for all field types
Attributes
| Attribute | Type | Description |
|---|
| empty_strings_allowed | boolean = true | Designates whether empty strings fundamentally are allowed at the database level. |
| empty_values | list = list(validators.EMPTY_VALUES) | A list of values that are considered empty for validation purposes. |
| creation_counter | integer = 0 | Used to retain order for all user-specified fields by tracking each time a Field instance is created. |
| auto_creation_counter | integer = -1 | Used to retain order for fields that Django implicitly creates by tracking each time an automatic Field instance is created. |
| default_validators | list = [] | Default set of validators applied to the field value during validation. |
| default_error_messages | dict | A dictionary containing default error messages for various validation failure states like null, blank, or invalid choices. |
| system_check_deprecated_details | dict = null | Stores metadata for system check warnings if the field type has been deprecated. |
| system_check_removed_details | dict = null | Stores metadata for system check errors if the field type has been removed from support. |
| non_db_attrs | tuple | Attributes that don't affect a column definition and are ignored when altering the field. |
| hidden | boolean = false | A flag indicating whether the field should be hidden from user-facing interfaces. |
| many_to_many | boolean = null | Boolean flag or metadata indicating if the field represents a many-to-many relationship. |
| many_to_one | boolean = null | Boolean flag or metadata indicating if the field represents a many-to-one relationship. |
| one_to_many | boolean = null | Boolean flag or metadata indicating if the field represents a one-to-many relationship. |
| one_to_one | boolean = null | Boolean flag or metadata indicating if the field represents a one-to-one relationship. |
| related_model | [Model](../base/model.md?sid=django_db_models_base_model) = null | The model class that this field is related to in a relational field context. |
| generated | boolean = false | Indicates whether the field value is generated by the database. |
| descriptor_class | class = DeferredAttribute | The class used to manage access to the field value on model instances. |
| description | string | Generic field type description, usually overridden by subclasses. |
Constructor
Signature
def Field(
verbose_name: string = null,
name: string = null,
primary_key: boolean = false,
max_length: integer = null,
unique: boolean = false,
blank: boolean = false,
null: boolean = false,
db_index: boolean = false,
rel: object = null,
default: any = NOT_PROVIDED,
editable: boolean = true,
serialize: boolean = true,
unique_for_date: string = null,
unique_for_month: string = null,
unique_for_year: string = null,
choices: iterable = null,
help_text: string = "",
db_column: string = null,
db_tablespace: string = null,
auto_created: boolean = false,
validators: iterable = (),
error_messages: dict = null,
db_comment: string = null,
db_default: any = NOT_PROVIDED
)
Parameters
| Name | Type | Description |
|---|
| verbose_name | string = null | A human-readable name for the field. |
| name | string = null | The name of the field used in the model. |
| primary_key | boolean = false | Whether this field is the primary key for the model. |
| max_length | integer = null | The maximum length of the field (for character fields). |
| unique | boolean = false | Whether the field value must be unique throughout the table. |
| blank | boolean = false | Whether the field is allowed to be blank in forms. |
| null | boolean = false | Whether the database should allow NULL values for this field. |
| db_index | boolean = false | Whether a database index should be created for this field. |
| rel | object = null | Used for relational fields to define the relationship. |
| default | any = NOT_PROVIDED | The default value for the field. |
| editable | boolean = true | Whether the field should be editable in the admin or other forms. |
| serialize | boolean = true | Whether the field should be serialized. |
| unique_for_date | string = null | Field name that this field must be unique for with respect to the date. |
| unique_for_month | string = null | Field name that this field must be unique for with respect to the month. |
| unique_for_year | string = null | Field name that this field must be unique for with respect to the year. |
| choices | iterable = null | An iterable of choices for this field. |
| help_text | string = "" | Extra help text to be displayed with the form widget. |
| db_column | string = null | The name of the database column to use for this field. |
| db_tablespace | string = null | The name of the database tablespace to use for this field's index. |
| auto_created | boolean = false | Whether this field was automatically created (e.g., an AutoField). |
| validators | iterable = () | A list of validators to apply to this field. |
| error_messages | dict = null | A dictionary of custom error messages. |
| db_comment | string = null | A comment for the database column. |
| db_default | any = NOT_PROVIDED | The database-side default value for the field. |
Methods
check()
@classmethod
def check(
**kwargs: dict
) - > list
Runs all system checks for the field, including name validation, choices, and database compatibility.
Parameters
| Name | Type | Description |
|---|
| **kwargs | dict | Contextual arguments for system checks such as available databases |
Returns
| Type | Description |
|---|
list | A list of check error or warning objects |
get_col()
@classmethod
def get_col(
alias: string,
output_field: object
) - > object
Returns a column expression for this field, using a cached version if the alias matches the model's table.
Parameters
| Name | Type | Description |
|---|
| alias | string | The table alias used in the SQL query |
| output_field | object | The field type to use for the output of the expression |
Returns
| Type | Description |
|---|
object | A Col expression object representing the database column |
choices()
@classmethod
def choices() - > iterable
Gets or sets the choices for the field, normalizing the input values upon assignment.
Returns
| Type | Description |
|---|
iterable | The normalized choices for the field |
cached_col()
@classmethod
def cached_col() - > object
Returns a cached Col expression for the field's primary model table.
Returns
| Type | Description |
|---|
object | A cached Col expression object |
@classmethod
def select_format(
compiler: object,
sql: string,
params: list
) - > tuple
Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django.
Parameters
| Name | Type | Description |
|---|
| compiler | object | The SQL compiler instance |
| sql | string | The original SQL string |
| params | list | The SQL parameters |
Returns
| Type | Description |
|---|
tuple | A tuple of (sql, params) for the select clause |
deconstruct()
@classmethod
def deconstruct() - > tuple
Return enough information to recreate the field as a 4-tuple.
Returns
| Type | Description |
|---|
tuple | A 4-tuple containing (name, path, args, kwargs) |
clone()
@classmethod
def clone() - > object
Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names.
Returns
| Type | Description |
|---|
object | A new instance of the same Field class with identical parameters |
get_pk_value_on_save()
@classmethod
def get_pk_value_on_save(
instance: object
) - > any
Hook to generate new PK values on save. This method is called when saving instances with no primary key value set.
Parameters
| Name | Type | Description |
|---|
| instance | object | The model instance being saved |
Returns
| Type | Description |
|---|
any | The generated primary key value or None |
to_python()
@classmethod
def to_python(
value: any
) - > any
Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted.
Parameters
| Name | Type | Description |
|---|
| value | any | The raw value to convert |
Returns
| Type | Description |
|---|
any | The converted Python object |
error_messages()
@classmethod
def error_messages() - > dict
Returns a dictionary of error messages for the field, merged across the class hierarchy.
Returns
| Type | Description |
|---|
dict | A mapping of error codes to message strings |
validators()
@classmethod
def validators() - > list
Provides a way to delay the creation of validators until they are required.
Returns
| Type | Description |
|---|
list | A list of all validator callables for the field |
run_validators()
@classmethod
def run_validators(
value: any
)
Executes all registered validators against the provided value and collects any validation errors.
Parameters
| Name | Type | Description |
|---|
| value | any | The value to validate |
validate()
@classmethod
def validate(
value: any,
model_instance: object
)
Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic.
Parameters
| Name | Type | Description |
|---|
| value | any | The value to check |
| model_instance | object | The instance of the model the value belongs to |
clean()
@classmethod
def clean(
value: any,
model_instance: object
) - > any
Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated.
Parameters
| Name | Type | Description |
|---|
| value | any | The raw value to clean |
| model_instance | object | The model instance associated with the value |
Returns
| Type | Description |
|---|
any | The cleaned and validated value |
db_type_parameters()
@classmethod
def db_type_parameters(
connection: object
) - > object
Returns a wrapper around the field's attributes for use in database type formatting.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
object | A DictWrapper containing field attributes |
db_check()
@classmethod
def db_check(
connection: object
) - > string
Return the database column check constraint for this field, for the provided connection.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
string | The SQL check constraint string or None |
db_type()
@classmethod
def db_type(
connection: object
) - > string
Return the database column data type for this field, for the provided connection.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
string | The SQL column type string |
rel_db_type()
@classmethod
def rel_db_type(
connection: object
) - > string
Return the data type that a related field pointing to this field should use.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
string | The SQL column type for related fields |
cast_db_type()
@classmethod
def cast_db_type(
connection: object
) - > string
Return the data type to use in the Cast() function.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
string | The SQL type string for casting |
db_parameters()
@classmethod
def db_parameters(
connection: object
) - > dict
Extension of db_type(), providing a range of different return values (type, checks).
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
dict | A dictionary containing 'type' and 'check' SQL strings |
db_type_suffix()
@classmethod
def db_type_suffix(
connection: object
) - > string
Returns the backend-specific type suffix for the field's internal type.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
string | The SQL type suffix string or None |
get_db_converters()
@classmethod
def get_db_converters(
connection: object
) - > list
Returns a list of functions used to convert values from the database to Python types.
Parameters
| Name | Type | Description |
|---|
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
list | A list of converter callables |
unique()
@classmethod
def unique() - > boolean
Returns whether the field must contain unique values, considering both the unique flag and primary key status.
Returns
| Type | Description |
|---|
boolean | True if the field is unique, False otherwise |
db_tablespace()
@classmethod
def db_tablespace() - > string
Returns the database tablespace to use for this field's index.
Returns
| Type | Description |
|---|
string | The name of the tablespace |
db_returning()
@classmethod
def db_returning() - > boolean
Private API intended only to be used by Django itself. Indicates if the field uses RETURNING for database defaults.
Returns
| Type | Description |
|---|
boolean | True if the field has a database default |
set_attributes_from_name()
@classmethod
def set_attributes_from_name(
name: string
)
Sets the field's name, attribute name, and column name based on the provided name string.
Parameters
| Name | Type | Description |
|---|
| name | string | The name of the field as defined on the model |
contribute_to_class()
@classmethod
def contribute_to_class(
cls: class,
name: string,
private_only: boolean
)
Register the field with the model class it belongs to.
Parameters
| Name | Type | Description |
|---|
| cls | class | The model class to which the field is being added |
| name | string | The name of the field |
| private_only | boolean | Whether to create a separate instance for every subclass |
get_filter_kwargs_for_object()
@classmethod
def get_filter_kwargs_for_object(
obj: object
) - > dict
Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has.
Parameters
| Name | Type | Description |
|---|
| obj | object | The model instance to extract the value from |
Returns
| Type | Description |
|---|
dict | A dictionary containing the field name and its value from the object |
get_attname()
@classmethod
def get_attname() - > string
Returns the attribute name used to access the field's value on a model instance.
Returns
| Type | Description |
|---|
string | The attribute name |
get_attname_column()
@classmethod
def get_attname_column() - > tuple
Returns a tuple of the attribute name and the database column name for the field.
Returns
| Type | Description |
|---|
tuple | A tuple of (attname, column) |
get_internal_type()
@classmethod
def get_internal_type() - > string
Returns the internal name of the field type, usually the class name.
Returns
| Type | Description |
|---|
string | The class name of the field |
pre_save()
@classmethod
def pre_save(
model_instance: object,
add: boolean
) - > any
Return field's value just before saving.
Parameters
| Name | Type | Description |
|---|
| model_instance | object | The instance being saved |
| add | boolean | True if the instance is being created, False if updated |
Returns
| Type | Description |
|---|
any | The value of the field from the model instance |
get_prep_value()
@classmethod
def get_prep_value(
value: any
) - > any
Perform preliminary non-db specific value checks and conversions.
Parameters
| Name | Type | Description |
|---|
| value | any | The value to prepare |
Returns
| Type | Description |
|---|
any | The value prepared for database-specific preparation |
get_db_prep_value()
@classmethod
def get_db_prep_value(
value: any,
connection: object,
prepared: boolean
) - > any
Return field's value prepared for interacting with the database backend.
Parameters
| Name | Type | Description |
|---|
| value | any | The value to prepare |
| connection | object | The current database connection |
| prepared | boolean | Whether get_prep_value has already been called |
Returns
| Type | Description |
|---|
any | The value formatted for the database driver |
get_db_prep_save()
@classmethod
def get_db_prep_save(
value: any,
connection: object
) - > any
Return field's value prepared for saving into a database.
Parameters
| Name | Type | Description |
|---|
| value | any | The value to prepare |
| connection | object | The current database connection |
Returns
| Type | Description |
|---|
any | The value prepared for a database save operation |
has_default()
@classmethod
def has_default() - > boolean
Return a boolean of whether this field has a default value.
Returns
| Type | Description |
|---|
boolean | True if a default value is provided |
has_db_default()
@classmethod
def has_db_default() - > boolean
Return a boolean of whether this field has a db_default value.
Returns
| Type | Description |
|---|
boolean | True if a database-level default is provided |
get_default()
@classmethod
def get_default() - > any
Return the default value for this field.
Returns
| Type | Description |
|---|
any | The default value or a callable that returns it |
get_choices()
@classmethod
def get_choices(
include_blank: boolean,
blank_choice: list,
limit_choices_to: dict,
ordering: tuple
) - > iterable
Return choices with a default blank choices included, for use as < select > choices for this field.
Parameters
| Name | Type | Description |
|---|
| include_blank | boolean | Whether to include an empty choice at the start |
| blank_choice | list | The specific choice to use for the blank option |
| limit_choices_to | dict | Filters for related model choices |
| ordering | tuple | Ordering for related model choices |
Returns
| Type | Description |
|---|
iterable | An iterator or list of (value, label) tuples |
value_to_string()
@classmethod
def value_to_string(
obj: object
) - > string
Return a string value of this field from the passed obj. This is used by the serialization framework.
Parameters
| Name | Type | Description |
|---|
| obj | object | The model instance to extract the value from |
Returns
| Type | Description |
|---|
string | The string representation of the field's value |
flatchoices()
@classmethod
def flatchoices() - > list
Returns a flattened list of the field's choices, removing any grouping.
Returns
| Type | Description |
|---|
list | A flat list of (value, label) tuples |
@classmethod
def save_form_data(
instance: object,
data: any
)
Updates the model instance with data received from a form field.
Parameters
| Name | Type | Description |
|---|
| instance | object | The model instance to update |
| data | any | The data to assign to the field |
@classmethod
def formfield(
form_class: class,
choices_form_class: class,
**kwargs: dict
) - > object
Return a django.forms.Field instance for this field.
Parameters
| Name | Type | Description |
|---|
| form_class | class | The form field class to instantiate |
| choices_form_class | class | The form field class to use if the field has choices |
| **kwargs | dict | Additional arguments for the form field constructor |
Returns
| Type | Description |
|---|
object | A Django form field instance |
value_from_object()
@classmethod
def value_from_object(
obj: object
) - > any
Return the value of this field in the given model instance.
Parameters
| Name | Type | Description |
|---|
| obj | object | The model instance to inspect |
Returns
| Type | Description |
|---|
any | The value of the field |
slice_expression()
@classmethod
def slice_expression(
expression: object,
start: integer,
length: integer
)
Return a slice of this field.
Parameters
| Name | Type | Description |
|---|
| expression | object | The expression to slice |
| start | integer | The start index |
| length | integer | The length of the slice |