Skip to main content

Field

Base class for all field types

Attributes

AttributeTypeDescription
empty_strings_allowedboolean = trueDesignates whether empty strings fundamentally are allowed at the database level.
empty_valueslist = list(validators.EMPTY_VALUES)A list of values that are considered empty for validation purposes.
creation_counterinteger = 0Used to retain order for all user-specified fields by tracking each time a Field instance is created.
auto_creation_counterinteger = -1Used to retain order for fields that Django implicitly creates by tracking each time an automatic Field instance is created.
default_validatorslist = []Default set of validators applied to the field value during validation.
default_error_messagesdictA dictionary containing default error messages for various validation failure states like null, blank, or invalid choices.
system_check_deprecated_detailsdict = nullStores metadata for system check warnings if the field type has been deprecated.
system_check_removed_detailsdict = nullStores metadata for system check errors if the field type has been removed from support.
non_db_attrstupleAttributes that don't affect a column definition and are ignored when altering the field.
hiddenboolean = falseA flag indicating whether the field should be hidden from user-facing interfaces.
many_to_manyboolean = nullBoolean flag or metadata indicating if the field represents a many-to-many relationship.
many_to_oneboolean = nullBoolean flag or metadata indicating if the field represents a many-to-one relationship.
one_to_manyboolean = nullBoolean flag or metadata indicating if the field represents a one-to-many relationship.
one_to_oneboolean = nullBoolean 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) = nullThe model class that this field is related to in a relational field context.
generatedboolean = falseIndicates whether the field value is generated by the database.
descriptor_classclass = DeferredAttributeThe class used to manage access to the field value on model instances.
descriptionstringGeneric 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

NameTypeDescription
verbose_namestring = nullA human-readable name for the field.
namestring = nullThe name of the field used in the model.
primary_keyboolean = falseWhether this field is the primary key for the model.
max_lengthinteger = nullThe maximum length of the field (for character fields).
uniqueboolean = falseWhether the field value must be unique throughout the table.
blankboolean = falseWhether the field is allowed to be blank in forms.
nullboolean = falseWhether the database should allow NULL values for this field.
db_indexboolean = falseWhether a database index should be created for this field.
relobject = nullUsed for relational fields to define the relationship.
defaultany = NOT_PROVIDEDThe default value for the field.
editableboolean = trueWhether the field should be editable in the admin or other forms.
serializeboolean = trueWhether the field should be serialized.
unique_for_datestring = nullField name that this field must be unique for with respect to the date.
unique_for_monthstring = nullField name that this field must be unique for with respect to the month.
unique_for_yearstring = nullField name that this field must be unique for with respect to the year.
choicesiterable = nullAn iterable of choices for this field.
help_textstring = ""Extra help text to be displayed with the form widget.
db_columnstring = nullThe name of the database column to use for this field.
db_tablespacestring = nullThe name of the database tablespace to use for this field's index.
auto_createdboolean = falseWhether this field was automatically created (e.g., an AutoField).
validatorsiterable = ()A list of validators to apply to this field.
error_messagesdict = nullA dictionary of custom error messages.
db_commentstring = nullA comment for the database column.
db_defaultany = NOT_PROVIDEDThe 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

NameTypeDescription
**kwargsdictContextual arguments for system checks such as available databases

Returns

TypeDescription
listA 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

NameTypeDescription
aliasstringThe table alias used in the SQL query
output_fieldobjectThe field type to use for the output of the expression

Returns

TypeDescription
objectA 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

TypeDescription
iterableThe 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

TypeDescription
objectA cached Col expression object

select_format()

@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

NameTypeDescription
compilerobjectThe SQL compiler instance
sqlstringThe original SQL string
paramslistThe SQL parameters

Returns

TypeDescription
tupleA 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

TypeDescription
tupleA 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

TypeDescription
objectA 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

NameTypeDescription
instanceobjectThe model instance being saved

Returns

TypeDescription
anyThe 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

NameTypeDescription
valueanyThe raw value to convert

Returns

TypeDescription
anyThe 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

TypeDescription
dictA 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

TypeDescription
listA 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

NameTypeDescription
valueanyThe 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

NameTypeDescription
valueanyThe value to check
model_instanceobjectThe 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

NameTypeDescription
valueanyThe raw value to clean
model_instanceobjectThe model instance associated with the value

Returns

TypeDescription
anyThe 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
objectA 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
stringThe 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
stringThe 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
stringThe 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
stringThe 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
dictA 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
stringThe 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

NameTypeDescription
connectionobjectThe current database connection

Returns

TypeDescription
listA 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

TypeDescription
booleanTrue 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

TypeDescription
stringThe 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

TypeDescription
booleanTrue 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

NameTypeDescription
namestringThe 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

NameTypeDescription
clsclassThe model class to which the field is being added
namestringThe name of the field
private_onlybooleanWhether 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

NameTypeDescription
objobjectThe model instance to extract the value from

Returns

TypeDescription
dictA 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

TypeDescription
stringThe 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

TypeDescription
tupleA 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

TypeDescription
stringThe 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

NameTypeDescription
model_instanceobjectThe instance being saved
addbooleanTrue if the instance is being created, False if updated

Returns

TypeDescription
anyThe 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

NameTypeDescription
valueanyThe value to prepare

Returns

TypeDescription
anyThe 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

NameTypeDescription
valueanyThe value to prepare
connectionobjectThe current database connection
preparedbooleanWhether get_prep_value has already been called

Returns

TypeDescription
anyThe 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

NameTypeDescription
valueanyThe value to prepare
connectionobjectThe current database connection

Returns

TypeDescription
anyThe 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

TypeDescription
booleanTrue 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

TypeDescription
booleanTrue if a database-level default is provided

get_default()

@classmethod
def get_default() - > any

Return the default value for this field.

Returns

TypeDescription
anyThe 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

NameTypeDescription
include_blankbooleanWhether to include an empty choice at the start
blank_choicelistThe specific choice to use for the blank option
limit_choices_todictFilters for related model choices
orderingtupleOrdering for related model choices

Returns

TypeDescription
iterableAn 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

NameTypeDescription
objobjectThe model instance to extract the value from

Returns

TypeDescription
stringThe 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

TypeDescription
listA flat list of (value, label) tuples

save_form_data()

@classmethod
def save_form_data(
instance: object,
data: any
)

Updates the model instance with data received from a form field.

Parameters

NameTypeDescription
instanceobjectThe model instance to update
dataanyThe data to assign to the field

formfield()

@classmethod
def formfield(
form_class: class,
choices_form_class: class,
**kwargs: dict
) - > object

Return a django.forms.Field instance for this field.

Parameters

NameTypeDescription
form_classclassThe form field class to instantiate
choices_form_classclassThe form field class to use if the field has choices
**kwargsdictAdditional arguments for the form field constructor

Returns

TypeDescription
objectA 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

NameTypeDescription
objobjectThe model instance to inspect

Returns

TypeDescription
anyThe value of the field

slice_expression()

@classmethod
def slice_expression(
expression: object,
start: integer,
length: integer
)

Return a slice of this field.

Parameters

NameTypeDescription
expressionobjectThe expression to slice
startintegerThe start index
lengthintegerThe length of the slice