Easy async ORM for Python, built with relations in mind
Model classes and field types for defining database schemas in Tortoise ORM. Models inherit from the base Model class and use field instances to define database columns with proper typing, validation, and relationships.
Base class that all ORM models inherit from, providing database operations, field management, and relationship handling.
class Model:
"""Base model class for database entities."""
def __init__(self, **kwargs):
"""
Initialize model instance with field values.
Args:
**kwargs: Field values as keyword arguments
"""
async def save(self):
"""
Save model instance to database (insert or update).
Returns:
Model: The saved model instance
"""
async def delete(self):
"""
Delete model instance from database.
Returns:
None
"""
async def refresh_from_db(self, fields=None):
"""
Refresh model instance from database.
Args:
fields (list, optional): Specific fields to refresh
"""
@classmethod
async def create(cls, **kwargs):
"""
Create and save new model instance.
Args:
**kwargs: Field values for the new instance
Returns:
Model: The created model instance
"""
@classmethod
async def get(cls, **kwargs):
"""
Get single model instance matching criteria.
Args:
**kwargs: Filter criteria
Returns:
Model: The matching model instance
Raises:
DoesNotExist: If no matching instance found
"""
@classmethod
async def get_or_none(cls, **kwargs):
"""
Get single model instance or None if not found.
Args:
**kwargs: Filter criteria
Returns:
Model or None: The matching model instance or None
"""
@classmethod
def all(cls):
"""
Get QuerySet for all instances of this model.
Returns:
QuerySet: QuerySet for all instances
"""
@classmethod
def filter(cls, **kwargs):
"""
Get filtered QuerySet.
Args:
**kwargs: Filter criteria
Returns:
QuerySet: Filtered QuerySet
"""
@classmethod
def exclude(cls, **kwargs):
"""
Get QuerySet excluding matching instances.
Args:
**kwargs: Exclusion criteria
Returns:
QuerySet: Filtered QuerySet
"""
@classmethod
def describe(cls, serializable=True):
"""
Describe model schema.
Args:
serializable (bool): Return JSON-serializable format
Returns:
dict: Model description
"""
class Meta:
"""Model metadata configuration."""
table = None # Custom table name
app = None # App label
abstract = False # Abstract model flag
unique_together = () # Unique constraint tuples
ordering = () # Default orderingField types for storing different kinds of data with validation and database mapping.
class IntField:
"""Integer field."""
def __init__(self, pk=False, unique=False, index=False, default=None, null=False, **kwargs): ...
class BigIntField:
"""Big integer field for large numbers."""
def __init__(self, pk=False, unique=False, index=False, default=None, null=False, **kwargs): ...
class SmallIntField:
"""Small integer field for small numbers."""
def __init__(self, pk=False, unique=False, index=False, default=None, null=False, **kwargs): ...
class FloatField:
"""Floating point number field."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...
class DecimalField:
"""Decimal field for precise decimal numbers."""
def __init__(self, max_digits, decimal_places, unique=False, index=False, default=None, null=False, **kwargs): ...class CharField:
"""Character field with maximum length."""
def __init__(self, max_length, unique=False, index=False, default=None, null=False, **kwargs): ...
class TextField:
"""Large text field for long text content."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...
class UUIDField:
"""UUID field for storing UUID values."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...class DateField:
"""Date field for storing dates."""
def __init__(self, unique=False, index=False, default=None, null=False, auto_now=False, auto_now_add=False, **kwargs): ...
class DatetimeField:
"""Datetime field for storing date and time."""
def __init__(self, unique=False, index=False, default=None, null=False, auto_now=False, auto_now_add=False, **kwargs): ...
class TimeField:
"""Time field for storing time values."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...
class TimeDeltaField:
"""Time delta field for storing time differences."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...class BooleanField:
"""Boolean field for true/false values."""
def __init__(self, default=None, null=False, **kwargs): ...
class BinaryField:
"""Binary field for storing binary data."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...
class JSONField:
"""JSON field for storing JSON data."""
def __init__(self, unique=False, index=False, default=None, null=False, **kwargs): ...class IntEnumField:
"""Integer enumeration field."""
def __init__(self, enum_type, unique=False, index=False, default=None, null=False, **kwargs): ...
class CharEnumField:
"""Character enumeration field."""
def __init__(self, enum_type, max_length=None, unique=False, index=False, default=None, null=False, **kwargs): ...Fields for defining relationships between models.
class ForeignKeyField:
"""Foreign key field for many-to-one relationships."""
def __init__(self, model_name, related_name=None, on_delete="CASCADE", to_field=None, **kwargs):
"""
Args:
model_name (str): Related model in "app.Model" format
related_name (str, optional): Name for reverse relation
on_delete (str): Deletion behavior ("CASCADE", "RESTRICT", "SET_NULL", "SET_DEFAULT", "NO_ACTION")
to_field (str, optional): Field to reference (defaults to pk)
"""class OneToOneField:
"""One-to-one field for one-to-one relationships."""
def __init__(self, model_name, related_name=None, on_delete="CASCADE", to_field=None, **kwargs):
"""
Args:
model_name (str): Related model in "app.Model" format
related_name (str, optional): Name for reverse relation
on_delete (str): Deletion behavior
to_field (str, optional): Field to reference (defaults to pk)
"""class ManyToManyField:
"""Many-to-many field for many-to-many relationships."""
def __init__(self, model_name, related_name=None, through=None, forward_key=None, backward_key=None, **kwargs):
"""
Args:
model_name (str): Related model in "app.Model" format
related_name (str, optional): Name for reverse relation
through (str, optional): Through table name
forward_key (str, optional): Forward foreign key name
backward_key (str, optional): Backward foreign key name
"""Classes for handling reverse relationship access and nullable relations.
class ForeignKeyRelation:
"""Descriptor for accessing foreign key related objects."""
class ForeignKeyNullableRelation:
"""Descriptor for accessing nullable foreign key related objects."""
class OneToOneRelation:
"""Descriptor for accessing one-to-one related objects."""
class OneToOneNullableRelation:
"""Descriptor for accessing nullable one-to-one related objects."""
class ManyToManyRelation:
"""Descriptor for accessing many-to-many related objects."""
class BackwardFKRelation:
"""Descriptor for reverse foreign key relationships."""
class BackwardOneToOneRelation:
"""Descriptor for reverse one-to-one relationships."""
class ReverseRelation:
"""Base class for reverse relationship descriptors."""Common field options available for all field types.
CASCADE = "CASCADE" # Delete related objects
RESTRICT = "RESTRICT" # Prevent deletion if related objects exist
SET_NULL = "SET_NULL" # Set foreign key to NULL
SET_DEFAULT = "SET_DEFAULT" # Set foreign key to default value
NO_ACTION = "NO_ACTION" # No action taken
class OnDelete:
"""Enumeration of deletion behavior constants."""
CASCADE = "CASCADE"
RESTRICT = "RESTRICT"
SET_NULL = "SET_NULL"
SET_DEFAULT = "SET_DEFAULT"
NO_ACTION = "NO_ACTION"class Field:
"""Base class for all field types."""
def __init__(self,
pk=False, # Primary key flag
unique=False, # Unique constraint
index=False, # Database index
default=None, # Default value
null=False, # Allow NULL values
description=None, # Field description
**kwargs): ...from tortoise.models import Model
from tortoise import fields
class User(Model):
id = fields.IntField(pk=True)
username = fields.CharField(max_length=20, unique=True)
email = fields.CharField(max_length=100, index=True)
full_name = fields.CharField(max_length=50, null=True)
created_at = fields.DatetimeField(auto_now_add=True)
updated_at = fields.DatetimeField(auto_now=True)
is_active = fields.BooleanField(default=True)
profile_data = fields.JSONField(default=dict)
class Meta:
table = "users"
ordering = ["-created_at"]
class Post(Model):
id = fields.IntField(pk=True)
title = fields.CharField(max_length=200)
content = fields.TextField()
author = fields.ForeignKeyField("models.User", related_name="posts")
created_at = fields.DatetimeField(auto_now_add=True)
tags = fields.ManyToManyField("models.Tag", related_name="posts")
class Meta:
table = "posts"
class Tag(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=50, unique=True)
class Meta:
table = "tags"# Create instances
user = await User.create(
username="alice",
email="alice@example.com",
full_name="Alice Smith"
)
post = await Post.create(
title="My First Post",
content="Hello world!",
author=user
)
# Get instances
user = await User.get(username="alice")
post = await Post.get(id=1)
# Update instances
user.full_name = "Alice Johnson"
await user.save()
# Delete instances
await post.delete()# Access foreign key relationships
post = await Post.get(id=1)
author = await post.author # Load related user
# Access reverse foreign key relationships
user = await User.get(id=1)
user_posts = await user.posts.all() # Get all posts by user
# Many-to-many relationships
tag = await Tag.create(name="python")
await post.tags.add(tag) # Add tag to post
post_tags = await post.tags.all() # Get all tags for postInstall with Tessl CLI
npx tessl i tessl/pypi-tortoise-orm