Skip to main content

Model

This class serves as the base for all database models, providing the core functionality for mapping Python objects to database tables. It handles instance initialization, state management, and lifecycle operations such as saving, deleting, and refreshing data from the database. The class also includes comprehensive validation logic for fields, unique constraints, and model-level consistency checks.

Attributes

AttributeTypeDescription
pkpropertyProxy property that provides access to the value of the model's primary key field.

Constructor

Signature

def Model(
*args: tuple,
**kwargs: dict
) - > null

Parameters

NameTypeDescription
*argstuplePositional arguments used to initialize model fields in the order they are defined.
**kwargsdictKeyword arguments representing field names and their corresponding values for initialization.

Methods


from_db()

@classmethod
def from_db(
db: str,
field_names: list,
values: list,
fetch_mode: str = null
) - > [Model](model.md?sid=django_db_models_base_model)

Creates a model instance from database values, bypassing the standard constructor to handle deferred fields and database state.

Parameters

NameTypeDescription
dbstrThe alias of the database the instance was loaded from.
field_nameslistThe names of the fields being loaded from the database.
valueslistThe raw values for the fields, in the order they appear in the model's concrete fields.
fetch_modestr = nullThe mode used to fetch the data, such as FETCH_ONE.

Returns

TypeDescription
[Model](model.md?sid=django_db_models_base_model)A new instance of the model populated with data from the database.

get_deferred_fields()

@classmethod
def get_deferred_fields() - > set

Return a set containing names of deferred fields for this instance.

Returns

TypeDescription
setA set of attribute names for fields that have not yet been loaded from the database.

refresh_from_db()

@classmethod
def refresh_from_db(
using: str = null,
fields: iterable = null,
from_queryset: [QuerySet](../query/queryset.md?sid=django_db_models_query_queryset) = null
)

Reload field values from the database. By default, the reloading happens from the database this instance was loaded from.

Parameters

NameTypeDescription
usingstr = nullThe database alias to use for the reload; overrides the default router.
fieldsiterable = nullAn iterable of field attribute names to specifically reload.
from_queryset[QuerySet](../query/queryset.md?sid=django_db_models_query_queryset) = nullA custom queryset to use for fetching the updated instance data.

arefresh_from_db()

@classmethod
def arefresh_from_db(
using: str = null,
fields: iterable = null,
from_queryset: [QuerySet](../query/queryset.md?sid=django_db_models_query_queryset) = null
) - > Coroutine

Asynchronously reload field values from the database by wrapping refresh_from_db.

Parameters

NameTypeDescription
usingstr = nullThe database alias to use for the reload.
fieldsiterable = nullSpecific field names to reload.
from_queryset[QuerySet](../query/queryset.md?sid=django_db_models_query_queryset) = nullA custom queryset to use for the fetch.

Returns

TypeDescription
CoroutineA coroutine that completes the database refresh.

serializable_value()

@classmethod
def serializable_value(
field_name: str
) - > any

Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object.

Parameters

NameTypeDescription
field_namestrThe name of the field whose serializable value is requested.

Returns

TypeDescription
anyThe raw field value or the primary key of a related object, suitable for serialization.

save()

@classmethod
def save(
force_insert: bool = false,
force_update: bool = false,
using: str = null,
update_fields: iterable = null
)

Save the current instance. Override this in a subclass if you want to control the saving process.

Parameters

NameTypeDescription
force_insertbool = falseIf True, forces the save to perform an SQL INSERT.
force_updatebool = falseIf True, forces the save to perform an SQL UPDATE.
usingstr = nullThe database alias to use for the save operation.
update_fieldsiterable = nullAn iterable of field names to update; if provided, only these fields are saved.

asave()

@classmethod
def asave(
force_insert: bool = false,
force_update: bool = false,
using: str = null,
update_fields: iterable = null
) - > Coroutine

Asynchronously save the current instance to the database.

Parameters

NameTypeDescription
force_insertbool = falseForces an SQL INSERT.
force_updatebool = falseForces an SQL UPDATE.
usingstr = nullThe database alias to use.
update_fieldsiterable = nullSpecific fields to update.

Returns

TypeDescription
CoroutineA coroutine that completes the save operation.

delete()

@classmethod
def delete(
using: str = null,
keep_parents: bool = false
) - > tuple

Removes the current instance from the database and handles related object cleanup.

Parameters

NameTypeDescription
usingstr = nullThe database alias to use for the deletion.
keep_parentsbool = falseIf True, prevents the deletion of parent model records in multi-table inheritance.

Returns

TypeDescription
tupleA tuple containing the total number of objects deleted and a dictionary with the count per object type.

adelete()

@classmethod
def adelete(
using: str = null,
keep_parents: bool = false
) - > Coroutine

Asynchronously removes the current instance from the database.

Parameters

NameTypeDescription
usingstr = nullThe database alias to use.
keep_parentsbool = falseWhether to preserve parent model records.

Returns

TypeDescription
CoroutineA coroutine that completes the deletion.

clean()

@classmethod
def clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields.


validate_unique()

@classmethod
def validate_unique(
exclude: iterable = null
)

Check unique constraints on the model and raise ValidationError if any failed.

Parameters

NameTypeDescription
excludeiterable = nullA collection of field names to exclude from uniqueness checks.

full_clean()

@classmethod
def full_clean(
exclude: iterable = null,
validate_unique: bool = true,
validate_constraints: bool = true
)

Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.

Parameters

NameTypeDescription
excludeiterable = nullField names to skip during the cleaning process.
validate_uniquebool = trueWhether to perform uniqueness validation.
validate_constraintsbool = trueWhether to perform model constraint validation.

clean_fields()

@classmethod
def clean_fields(
exclude: iterable = null
)

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

Parameters

NameTypeDescription
excludeiterable = nullField names to exclude from individual field validation.

check()

@classmethod
def check(
kwargs: dict
) - > list

Runs system checks on the model to identify configuration errors, field clashes, or database incompatibilities.

Parameters

NameTypeDescription
kwargsdictAdditional arguments for the check framework, such as 'databases'.

Returns

TypeDescription
listA list of check error and warning objects.