| [ Web Proxy ] |
| Viewing: https://tortoise.github.io/fields.html#fields | [Back] [Original] |
[logo]
Fields are defined as properties of a Model class object:
from tortoise.models import Model
from tortoise import fields
class Tournament(Model):
id = fields.IntField(primary_key=True)
name = fields.CharField(max_length=255)
Here is the list of fields available with custom options of these fields:
Sentinel indicating that the database should apply its default value.
When a field has db_default and the user does not provide a value,
this object is set as the attribute value on the model instance.
During INSERT compilation it is detected via isinstance() checks:
- Single-insert path: columns with DatabaseDefault are omitted from the
INSERT statement, so the DB applies its DEFAULT.
Bulk-insert path: columns where all instances hold DatabaseDefault
are omitted; mixed usage raises OperationalError.
Returns False so that if instance.field: is falsy for unset db_default fields.
This is consistent with no value has been set yet. Users who need to
distinguish between DatabaseDefault and other falsy values should use
isinstance(value, DatabaseDefault).
None, generated=False, primary_key=None, null=False, default=None, db_default=NOT_PROVIDED, unique=False, db_index=None, description=None, model=None, validators=None, **kwargs)[source]Base Field type.
NoneProvide a source_field name if the DB column name needs to be something specific instead of generated off the field name.
FalseIs this field DB-generated?
NoneIs this field a Primary Key? Can only have a single such field on the Model,
and if none is specified it will autogenerate a default primary key called id.
FalseIs this field nullable?
NoneA default value for the field if not specified on Model creation. This can also be a callable for dynamic defaults in which case we will call it. The default value will not be part of the schema.
NOT_PROVIDEDA database-level default value. This can be a static value or an
instance of SqlDefault
FalseIs this field unique?
NoneShould this field be indexed by itself?
NoneField description. Will also appear in Tortoise.describe_model()
and as DB comments in the generated DDL.
NoneValidators for this field.
Class Attributes: These attributes needs to be defined when defining an actual field type.
The Python type the field is. If adding a type as a mixin, _FieldMeta will automatically set this to that.
Does this field have a direct corresponding DB column? Or is the field virtualized?
If the DB driver natively supports this Python type, should we skip it? This is for optimization purposes only, where we dont need to force type conversion between Python and the DB.
A casting term that we need to apply in case the DB needs emulation help.
The SQL that instructs the DB to auto-generate this field.
Required if allows_generated is True.
Per-DB overrides:
One can specify per-DB overrides of any of the class attributes,
or the to_db_value or to_python_value methods.
To do so, specify a inner class in the form of class _db__SQL_DIALECT: like so:
class _db_sqlite:
SQL_TYPE = "VARCHAR(40)"
skip_to_python_if_native = False
def function_cast(self, term: Term) -> Term:
return functions.Cast(term, SqlTypes.NUMERIC)
Tortoise will then use the overridden attributes/functions for that dialect. If you need a dynamic attribute, you can use a property.
Returns a dict with constraints defined in the Pydantic/JSONSchema format.
Describes the field.
dict
A dictionary containing the field description.
(This assumes serializable=True, which is the default):
{
"name": str # Field name
"field_type": str # Field type
"db_column": str # Name of DB column
# Optional: Only for pk/data fields
"raw_field": str # Name of raw field of the Foreign Key
# Optional: Only for Foreign Keys
"db_field_types": dict # DB Field types for default and DB overrides
"python_type": str # Python type
"generated": bool # Is the field generated by the DB?
"nullable": bool # Is the column nullable?
"unique": bool # Is the field unique?
"indexed": bool # Is the field indexed?
"default": ... # The default value (coerced to int/float/str/bool/null)
"description": str # Description of the field (nullable)
"docstring": str # Field docstring (nullable)
}
When serializable=False is specified some fields are not coerced to valid
JSON types. The changes are:
{
"field_type": Field # The Field class used
"python_type": Type # The actual Python type
"default": ... # The default value as native type OR a callable
}
Return a DatabaseDefault instance if this field has a db_default, else None.
Returns the DB field type for this field for the current dialect.
Returns the DB types for this field.
Returns True if the field is required to be provided.
It needs to be non-nullable and not have a default or be DB-generated to be required.
Converts from the Python type to the DB type.
Current python value in model.
Model class or Model instance provided to look up.
Due to metacoding, to determine if this is an instance reliably, please do a:
if hasattr(instance, "_saved_in_db"):
Any
Validate whether given value is valid
ValidationError If validator check is not passed
None
An enumeration.
Returns format using actual value type unless __str__ has been overridden.
None, *, null: False = False, **kwargs: Any)[source]None, *, null: True, **kwargs: Any)Big integer field. (64-bit signed)
primary_key (bool):True if field is Primary Key.
False, **kwargs: Any)[source]Binary field.
This is for storing bytes objects.
Note that filter or queryset-update operations are not supported.
False, **kwargs: Any)[source]Boolean field.
None, max_length=0, **kwargs)[source]Char Enum Field
A field representing a character enumeration.
Warning: If max_length is not specified or equals to zero, the size of represented
char fields is automatically detected. So if later you update the enum, you need to update your
table schema as well.
Note: Valid str value of enum_type is acceptable.
enum_type:The enum class
description:The description of the field. It is set automatically if not specified to a multiline list of name: value pairs.
max_length:The length of the created CharField. If it is zero it is automatically detected from enum_type.
False, **kwargs: Any)[source]Character field.
You must provide the following:
max_length (int):Maximum length of the field in characters.
False, **kwargs: Any)[source]Date field.
False, auto_now_add: bool = False, *, null: False = False, **kwargs: Any)[source]False, auto_now_add: bool = False, *, null: True, **kwargs: Any)Datetime field.
auto_now and auto_now_add is exclusive.
You can opt to set neither or only ONE of them.
auto_now (bool):Always set to datetime.utcnow() on save.
auto_now_add (bool):Set to datetime.utcnow() on first save only.
Returns a dict with constraints defined in the Pydantic/JSONSchema format.
Describes the field.
dict
A dictionary containing the field description.
(This assumes serializable=True, which is the default):
{
"name": str # Field name
"field_type": str # Field type
"db_column": str # Name of DB column
# Optional: Only for pk/data fields
"raw_field": str # Name of raw field of the Foreign Key
# Optional: Only for Foreign Keys
"db_field_types": dict # DB Field types for default and DB overrides
"python_type": str # Python type
"generated": bool # Is the field generated by the DB?
"nullable": bool # Is the column nullable?
"unique": bool # Is the field unique?
"indexed": bool # Is the field indexed?
"default": ... # The default value (coerced to int/float/str/bool/null)
"description": str # Description of the field (nullable)
"docstring": str # Field docstring (nullable)
}
When serializable=False is specified some fields are not coerced to valid
JSON types. The changes are:
{
"field_type": Field # The Field class used
"python_type": Type # The actual Python type
"default": ... # The default value as native type OR a callable
}
False, **kwargs: Any)[source]Accurate decimal field.
You must provide the following:
max_digits (int):Max digits of significance of the decimal field.
decimal_places (int):How many of those significant digits is after the decimal point.
False, **kwargs: Any)[source]Float (double) field.
None, **kwargs)[source]Enum Field
A field representing an integer enumeration.
The description of the field is set automatically if not specified to a multiline list of name: value pairs.
Note: Valid int value of enum_type is acceptable.
enum_type:The enum class
description:The description of the field. It is set automatically if not specified to a multiline list of name: value pairs.
None, *, null: False = False, **kwargs: Any)[source]None, *, null: True, **kwargs: Any)Integer field. (32-bit signed)
primary_key (bool):True if field is Primary Key.
JSON field.
This field can store dictionaries or lists of any JSON-compliant structure.
You can use generics to make static checking more friendly. Example: JSONField[dict[str, str]]
You can specify your own custom JSON encoder/decoder, leaving at the default should work well.
If you have orjson installed, we default to using that,
else the default json module will be used.
encoder:The custom JSON encoder.
decoder:The custom JSON decoder.
If you want to use Pydantic model as the field type for generating a better OpenAPI documentation, you can use field_type to specify the type of the field.
field_type:The Pydantic model class.
None, *, null: False = False, **kwargs: Any)[source]None, *, null: True, **kwargs: Any)Small integer field. (16-bit signed)
primary_key (bool):True if field is Primary Key.
None, unique=False, db_index=False, **kwargs)[source]Large Text field.
False, **kwargs: Any)[source]A field for storing time differences.
False, auto_now_add: bool = False, *, null: False = False, **kwargs: Any)[source]False, auto_now_add: bool = False, *, null: True, **kwargs: Any)Time field.
False, **kwargs: Any)[source]UUID Field
This field can store uuid value.
If used as a primary key, it will auto-generate a UUID4 by default.
None, on_delete: OnDelete = CASCADE, db_constraint: bool = True, *, null: True, **kwargs: Any) ForeignKeyFieldInstance[MODEL] | None[source]None, on_delete: OnDelete = CASCADE, db_constraint: bool = True, null: False = False, **kwargs: Any) ForeignKeyFieldInstance[MODEL]ForeignKey relation field.
This field represents a foreign key relation to another model.
See Foreign Key for usage information.
You must provide the following:
to:The related model or name of the related model in a 'app.model' format.
The following is optional:
related_name:The attribute name on the related model to reverse resolve the foreign key.
on_delete:field.CASCADE:Indicate that the model should be cascade deleted if related model gets deleted.
field.RESTRICT:Indicate that the related model delete will be restricted as long as a foreign key points to it.
field.SET_NULL:Resets the field to NULL in case the related model gets deleted.
Can only be set if field has null=True set.
field.SET_DEFAULT:Resets the field to default value in case the related model gets deleted.
Can only be set is field has a default set.
field.NO_ACTION:Take no action.
to_field:The attribute name on the related model to establish foreign key relationship. If not set, pk is used
db_constraint:Controls whether or not a constraint should be created in the database for this foreign key. The default is True, and thats almost certainly what you want; setting this to False can be very bad for data integrity.
None, forward_key=None, backward_key='', related_name='', on_delete=OnDelete.CASCADE, db_constraint=True, unique=True, **kwargs)[source]ManyToMany relation field.
This field represents a many-to-many between this model and another model.
See Many to Many for usage information.
You must provide the following:
to:The related model or name of the related model in a 'app.model' format.
The following is optional:
through:The DB table that represents the through table. The default is normally safe.
forward_key:The forward lookup key on the through table. The default is normally safe.
backward_key:The backward lookup key on the through table. The default is normally safe.
related_name:The attribute name on the related model to reverse resolve the many to many.
db_constraint:Controls whether or not a constraint should be created in the database for this foreign key. The default is True, and thats almost certainly what you want; setting this to False can be very bad for data integrity.
on_delete:field.CASCADE:Indicate that the model should be cascade deleted if related model gets deleted.
field.RESTRICT:Indicate that the related model delete will be restricted as long as a foreign key points to it.
field.SET_NULL:Resets the field to NULL in case the related model gets deleted.
Can only be set if field has null=True set.
field.SET_DEFAULT:Resets the field to default value in case the related model gets deleted.
Can only be set is field has a default set.
field.NO_ACTION:Take no action.
unique:Controls whether or not a unique index should be created in the database to speed up select queries. The default is True. If you want to allow repeat records, set this to False.
ManyToManyRelation[Any]
None, on_delete: OnDelete = CASCADE, db_constraint: bool = True, *, null: True, **kwargs: Any) OneToOneFieldInstance[MODEL] | None[source]None, on_delete: OnDelete = CASCADE, db_constraint: bool = True, null: False = False, **kwargs: Any) OneToOneFieldInstance[MODEL]OneToOne relation field.
This field represents a foreign key relation to another model.
See One to One for usage information.
You must provide the following:
to:The related model or name of the related model in a 'app.model' format.
The following is optional:
related_name:The attribute name on the related model to reverse resolve the foreign key.
on_delete:field.CASCADE:Indicate that the model should be cascade deleted if related model gets deleted.
field.RESTRICT:Indicate that the related model delete will be restricted as long as a foreign key points to it.
field.SET_NULL:Resets the field to NULL in case the related model gets deleted.
Can only be set if field has null=True set.
field.SET_DEFAULT:Resets the field to default value in case the related model gets deleted.
Can only be set is field has a default set.
field.NO_ACTION:Take no action.
to_field:The attribute name on the related model to establish foreign key relationship. If not set, pk is used
db_constraint:Controls whether or not a constraint should be created in the database for this foreign key. The default is True, and thats almost certainly what you want; setting this to False can be very bad for data integrity.
Convenience subclass of SqlDefault that emits CURRENT_TIMESTAMP.
Example:
class MyModel(Model):
created_at = fields.DatetimeField(db_default=Now())
Convenience subclass of SqlDefault that emits a dialect-specific
expression for generating a random 32-character hex string.
Example:
class MyModel(Model):
tracking_id = fields.CharField(max_length=36, db_default=RandomHex())
Represents a raw SQL expression for use as a database-level default value.
Use this with the db_default parameter on fields to emit raw SQL
in both generate_schemas() and migrations.
Warning
The SQL string is emitted verbatim into DDL statements. Never construct it from untrusted user input.
Note
For common expressions that differ across database dialects, prefer the
provided convenience subclasses (Now, RandomHex) over
raw SQL strings. For example, MySQL requires CURRENT_TIMESTAMP(6)
for DATETIME(6) columns, which Now handles automatically.
Example:
class MyModel(Model):
counter = fields.IntField(db_default=SqlDefault("0"))
created_at = fields.DatetimeField(db_default=Now())
None, generated=False, primary_key=None, null=False, default=None, db_default=NOT_PROVIDED, unique=False, db_index=None, description=None, model=None, validators=None, **kwargs)[source]True, **kwargs)[source]UUID Field
This field can store uuid value, but with the option to add binary compression.
If used as a primary key, it will auto-generate a UUID4 by default.
binary_compression (bool):If True, the UUID will be stored in binary format. This will save 6 bytes per UUID in the database. Note: that this is a MySQL-only feature. See https://dev.mysql.com/blog-archive/mysql-8-0-uuid-support/ for more details.
Converts from the Python type to the DB type.
Current python value in model.
Model class or Model instance provided to look up.
Due to metacoding, to determine if this is an instance reliably, please do a:
if hasattr(instance, "_saved_in_db"):
str | bytes | None
None, config=None, weights=None, stored=True, **kwargs)[source]Describes the field.
dict
A dictionary containing the field description.
(This assumes serializable=True, which is the default):
{
"name": str # Field name
"field_type": str # Field type
"db_column": str # Name of DB column
# Optional: Only for pk/data fields
"raw_field": str # Name of raw field of the Foreign Key
# Optional: Only for Foreign Keys
"db_field_types": dict # DB Field types for default and DB overrides
"python_type": str # Python type
"generated": bool # Is the field generated by the DB?
"nullable": bool # Is the column nullable?
"unique": bool # Is the field unique?
"indexed": bool # Is the field indexed?
"default": ... # The default value (coerced to int/float/str/bool/null)
"description": str # Description of the field (nullable)
"docstring": str # Field docstring (nullable)
}
When serializable=False is specified some fields are not coerced to valid
JSON types. The changes are:
{
"field_type": Field # The Field class used
"python_type": Type # The actual Python type
"default": ... # The default value as native type OR a callable
}
It is possible to subclass fields allowing use of arbitrary types as long as they can be represented in a
database compatible format. An example of this would be a simple wrapper around the CharField
to store and query Enum types.
from enum import Enum
from typing import Type
from tortoise import ConfigurationError
from tortoise.fields import CharField
class EnumField(CharField):
"""
An example extension to CharField that serializes Enums
to and from a str representation in the DB.
"""
def __init__(self, enum_type: Type[Enum], **kwargs):
super().__init__(128, **kwargs)
if not issubclass(enum_type, Enum):
raise ConfigurationError("{} is not a subclass of Enum!".format(enum_type))
self._enum_type = enum_type
def to_db_value(self, value: Enum, instance) -> str:
return value.value
def to_python_value(self, value: str) -> Enum:
try:
return self._enum_type(value)
except Exception:
raise ValueError(
"Database value {} does not exist on Enum {}.".format(value, self._enum_type)
)
When subclassing, make sure that the to_db_value returns the same type as the superclass (in the case of CharField,
that is a str) and that, naturally, to_python_value accepts the same type in the value parameter (also str).
| Web Proxy Viewer | New URL | Original Page |