Skip to content

ORM API Reference

This page provides detailed API documentation for fast-django's ORM components, which are re-exported from Tortoise ORM.

Models

Model

class Model:
    # Base model class for all database models

Base model class for defining database models.

Example:

from fast_django.orm import Model, fields

class User(Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=50)
    email = fields.CharField(max_length=100)

Fields

Field Types

IntField

IntField(pk: bool = False, null: bool = False, default: Any = None, unique: bool = False, index: bool = False, description: str = None)

Integer field for storing whole numbers.

Parameters: - pk (bool): Primary key field. - null (bool): Allow NULL values. - default (Any): Default value. - unique (bool): Unique constraint. - index (bool): Create database index. - description (str): Field description.

CharField

CharField(max_length: int, null: bool = False, default: Any = None, unique: bool = False, index: bool = False, description: str = None)

Character field for storing strings with maximum length.

Parameters: - max_length (int): Maximum string length. - null (bool): Allow NULL values. - default (Any): Default value. - unique (bool): Unique constraint. - index (bool): Create database index. - description (str): Field description.

TextField

TextField(null: bool = False, default: Any = None, description: str = None)

Text field for storing long text content.

Parameters: - null (bool): Allow NULL values. - default (Any): Default value. - description (str): Field description.

BooleanField

BooleanField(null: bool = False, default: bool = False, description: str = None)

Boolean field for storing true/false values.

Parameters: - null (bool): Allow NULL values. - default (bool): Default value. - description (str): Field description.

DateTimeField

DateTimeField(null: bool = False, default: Any = None, auto_now: bool = False, auto_now_add: bool = False, description: str = None)

DateTime field for storing date and time values.

Parameters: - null (bool): Allow NULL values. - default (Any): Default value. - auto_now (bool): Update on every save. - auto_now_add (bool): Set on creation only. - description (str): Field description.

ForeignKeyField

ForeignKeyField(model_name: str, related_name: str = None, null: bool = False, on_delete: str = "CASCADE", description: str = None)

Foreign key field for model relationships.

Parameters: - model_name (str): Related model name. - related_name (str): Reverse relationship name. - null (bool): Allow NULL values. - on_delete (str): On delete behavior. - description (str): Field description.

ManyToManyField

ManyToManyField(model_name: str, related_name: str = None, through: str = None, description: str = None)

Many-to-many field for model relationships.

Parameters: - model_name (str): Related model name. - related_name (str): Reverse relationship name. - through (str): Through model name. - description (str): Field description.

Database Operations

Tortoise

class Tortoise:
    @staticmethod
    async def init(config: dict, generate_schemas: bool = False) -> None
    @staticmethod
    async def close_connections() -> None
    @staticmethod
    def get_connection(connection_name: str = "default") -> BaseDBAsyncClient

Tortoise ORM main class for database management.

Methods: - init(config): Initialize database connections. - close_connections(): Close all database connections. - get_connection(name): Get database connection.

run_async

def run_async(coroutine: Coroutine) -> Any

Run async coroutine in sync context.

Parameters: - coroutine (Coroutine): Async coroutine to run.

Returns: - Any: Coroutine result.

Query Operations

Model Methods

all()

async def all() -> QuerySet

Get all model instances.

Returns: - QuerySet: Query set for all instances.

get(**kwargs)

async def get(**kwargs) -> Model

Get single model instance by filters.

Parameters: - **kwargs: Field filters.

Returns: - Model: Model instance.

Raises: - DoesNotExist: If no instance found.

filter(**kwargs)

def filter(**kwargs) -> QuerySet

Filter model instances by field values.

Parameters: - **kwargs: Field filters.

Returns: - QuerySet: Filtered query set.

create(**kwargs)

async def create(**kwargs) -> Model

Create new model instance.

Parameters: - **kwargs: Field values.

Returns: - Model: Created model instance.

bulk_create(objects: list[Model])

async def bulk_create(objects: list[Model]) -> list[Model]

Create multiple model instances efficiently.

Parameters: - objects (list[Model]): List of model instances.

Returns: - list[Model]: Created model instances.

QuerySet Methods

order_by(*fields)

def order_by(*fields: str) -> QuerySet

Order query set by fields.

Parameters: - *fields (str): Field names to order by.

Returns: - QuerySet: Ordered query set.

limit(count: int)

def limit(count: int) -> QuerySet

Limit number of results.

Parameters: - count (int): Maximum number of results.

Returns: - QuerySet: Limited query set.

offset(count: int)

def offset(count: int) -> QuerySet

Skip number of results.

Parameters: - count (int): Number of results to skip.

Returns: - QuerySet: Offset query set.

prefetch_related(*fields)

def prefetch_related(*fields: str) -> QuerySet

Prefetch related objects to avoid N+1 queries.

Parameters: - *fields (str): Related field names.

Returns: - QuerySet: Query set with prefetched relations.

update(**kwargs)

async def update(**kwargs) -> int

Update all instances in query set.

Parameters: - **kwargs: Field updates.

Returns: - int: Number of updated instances.

delete()

async def delete() -> int

Delete all instances in query set.

Returns: - int: Number of deleted instances.

Instance Methods

save()

async def save() -> None

Save model instance to database.

delete()

async def delete() -> None

Delete model instance from database.

update_from_dict(data: dict)

def update_from_dict(data: dict) -> None

Update instance fields from dictionary.

Parameters: - data (dict): Field values dictionary.

Relationships

Foreign Key

# Access related object
user = await User.get(id=1)
posts = await user.posts.all()

# Create with related object
post = await Post.create(title="Hello", author=user)

Many-to-Many

# Add related objects
post = await Post.get(id=1)
tag = await Tag.get(name="python")
await post.tags.add(tag)

# Remove related objects
await post.tags.remove(tag)

# Clear all related objects
await post.tags.clear()

# Get related objects
tags = await post.tags.all()

Transactions

in_transaction

async def in_transaction() -> AsyncContextManager

Transaction context manager.

Example:

from fast_django.orm import in_transaction

async with in_transaction():
    user = await User.create(username="john")
    post = await Post.create(title="Hello", author=user)

Exceptions

DoesNotExist

class DoesNotExist(Exception):
    pass

Raised when model instance is not found.

IntegrityError

class IntegrityError(Exception):
    pass

Raised when database integrity constraint is violated.

ValidationError

class ValidationError(Exception):
    pass

Raised when model validation fails.