Comprehensive type stubs for Django framework enabling static type checking with mypy
—
Django's migrations system provides version control for database schema changes, enabling automated creation, modification, and rollback of database structures with type-safe migration operations.
# Migration base classes
from django.db import migrations
from django.db.migrations import Migration, swappable_dependency
# Migration operations
from django.db.migrations.operations import (
# Model operations
CreateModel, DeleteModel, RenameModel,
AlterModelOptions, AlterModelTable, AlterModelManagers,
# Field operations
AddField, RemoveField, AlterField, RenameField,
# Index and constraint operations
AddIndex, RemoveIndex, RenameIndex, AddConstraint, RemoveConstraint,
AlterIndexTogether, AlterUniqueTogether, AlterOrderWithRespectTo,
# Special operations
RunSQL, RunPython, SeparateDatabaseAndState
)
# Migration management
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.recorder import MigrationRecorder
from django.db.migrations.state import ProjectState, ModelState
from django.db.migrations.graph import MigrationGraphCore migration class defining database schema changes and their execution order.
class Migration:
"""
Base class representing a single database migration with operations.
Attributes:
operations: List of migration operations to perform
dependencies: List of (app_label, migration_name) tuples this migration depends on
run_before: List of migrations that should run after this one
replaces: List of migrations this migration replaces
initial: Whether this is an initial migration
atomic: Whether to run operations in a transaction
name: Migration name
app_label: App this migration belongs to
"""
operations: Sequence[Operation]
dependencies: Sequence[tuple[str, str]]
run_before: Sequence[tuple[str, str]]
replaces: Sequence[tuple[str, str]]
initial: bool | None
atomic: bool
name: str
app_label: str
def __init__(self, name: str, app_label: str) -> None: ...
def mutate_state(self, project_state: ProjectState, preserve: bool = False) -> ProjectState: ...
def apply(self, project_state: ProjectState, schema_editor: BaseDatabaseSchemaEditor, collect_sql: bool = False) -> ProjectState: ...
def unapply(self, project_state: ProjectState, schema_editor: BaseDatabaseSchemaEditor, collect_sql: bool = False) -> ProjectState: ...Operations for creating, modifying, and deleting models.
class CreateModel(Operation):
"""Create a new model with specified fields and options."""
def __init__(self, name: str, fields: list[tuple[str, Field]], options: dict = None, bases: tuple = None, managers: list = None) -> None: ...
class DeleteModel(Operation):
"""Delete an existing model and its database table."""
def __init__(self, name: str) -> None: ...
class RenameModel(Operation):
"""Rename a model and its database table."""
def __init__(self, old_name: str, new_name: str) -> None: ...
class AlterModelOptions(Operation):
"""Change model Meta options (permissions, ordering, etc.)."""
def __init__(self, name: str, options: dict) -> None: ...
class AlterModelTable(Operation):
"""Change the database table name for a model."""
def __init__(self, name: str, table: str) -> None: ...
class AlterModelManagers(Operation):
"""Change the managers available on a model."""
def __init__(self, name: str, managers: list) -> None: ...Operations for adding, removing, and modifying model fields.
class AddField(Operation):
"""Add a new field to a model."""
def __init__(self, model_name: str, name: str, field: Field, preserve_default: bool = True) -> None: ...
class RemoveField(Operation):
"""Remove a field from a model."""
def __init__(self, model_name: str, name: str) -> None: ...
class AlterField(Operation):
"""Change the definition of a field."""
def __init__(self, model_name: str, name: str, field: Field, preserve_default: bool = True) -> None: ...
class RenameField(Operation):
"""Rename a field in a model."""
def __init__(self, model_name: str, old_name: str, new_name: str) -> None: ...Operations for managing database indexes and constraints.
class AddIndex(Operation):
"""Add a database index."""
def __init__(self, model_name: str, index: Index) -> None: ...
class RemoveIndex(Operation):
"""Remove a database index."""
def __init__(self, model_name: str, name: str) -> None: ...
class RenameIndex(Operation):
"""Rename a database index."""
def __init__(self, model_name: str, old_name: str, new_name: str) -> None: ...
class AddConstraint(Operation):
"""Add a database constraint."""
def __init__(self, model_name: str, constraint: BaseConstraint) -> None: ...
class RemoveConstraint(Operation):
"""Remove a database constraint."""
def __init__(self, model_name: str, name: str) -> None: ...
class AlterIndexTogether(Operation):
"""Change the index_together option for a model."""
def __init__(self, name: str, index_together: set[tuple[str, ...]]) -> None: ...
class AlterUniqueTogether(Operation):
"""Change the unique_together option for a model."""
def __init__(self, name: str, unique_together: set[tuple[str, ...]]) -> None: ...Operations for custom SQL and Python code execution.
class RunSQL(Operation):
"""Execute raw SQL during migration."""
def __init__(self, sql: str | list[str], reverse_sql: str | list[str] = None, state_operations: list[Operation] = None, hints: dict = None, elidable: bool = False) -> None: ...
class RunPython(Operation):
"""Execute Python code during migration."""
def __init__(self, code: callable, reverse_code: callable = None, atomic: bool = None, hints: dict = None, elidable: bool = False) -> None: ...
class SeparateDatabaseAndState(Operation):
"""Separate database operations from state changes."""
def __init__(self, database_operations: list[Operation] = None, state_operations: list[Operation] = None) -> None: ...Classes for loading, executing, and managing migrations.
class MigrationExecutor:
"""Executes migrations against a database."""
def __init__(self, connection, progress_callback: callable = None) -> None: ...
def migration_plan(self, targets: list[tuple[str, str]], clean_start: bool = False) -> list[tuple[Migration, bool]]: ...
def migrate(self, targets: list[tuple[str, str]], plan: list[tuple[Migration, bool]] = None, state: ProjectState = None, fake: bool = False, fake_initial: bool = False) -> ProjectState: ...
class MigrationAutodetector:
"""Detects changes between model states and generates migrations."""
def __init__(self, from_state: ProjectState, to_state: ProjectState, questioner: MigrationQuestioner = None) -> None: ...
def changes(self, graph: MigrationGraph, trim_to_apps: set[str] = None, convert_apps: set[str] = None, migration_name: str = None) -> dict[str, list[Migration]]: ...
class MigrationLoader:
"""Loads migration files from disk."""
def __init__(self, connection, load: bool = True, ignore_no_migrations: bool = False) -> None: ...
def get_migration_by_prefix(self, app_label: str, name_prefix: str) -> Migration: ...
class MigrationRecorder:
"""Records which migrations have been applied."""
def __init__(self, connection) -> None: ...
def record_applied(self, app: str, name: str) -> None: ...
def record_unapplied(self, app: str, name: str) -> None: ...
def applied_migrations(self) -> set[tuple[str, str]]: ...Classes representing the state of the project and models during migration.
class ProjectState:
"""Represents the state of the entire project at a point in migration history."""
def __init__(self, models: dict = None, real_apps: set[str] = None) -> None: ...
def add_model(self, model_state: ModelState) -> None: ...
def remove_model(self, app_label: str, model_name: str) -> None: ...
def reload_model(self, app_label: str, model_name: str, delay: bool = False) -> None: ...
def clone(self) -> ProjectState: ...
class ModelState:
"""Represents the state of a single model at a point in migration history."""
def __init__(self, app_label: str, name: str, fields: list[tuple[str, Field]], options: dict = None, bases: tuple = None, managers: list = None) -> None: ...
def clone(self) -> ModelState: ...
def render(self, apps: Apps) -> type[Model]: ...def swappable_dependency(value: str) -> SwappableTuple:
"""Create a dependency that can be swapped for a different model."""
class SwappableTuple(tuple[str, str]):
"""Tuple representing a swappable model dependency."""
setting: str
def __new__(cls, value: tuple[str, str], setting: str) -> SwappableTuple: ...# Migration-specific exceptions
class InvalidMigrationPlan(Exception): ...
class IrreversibleError(RuntimeError): ...
class NodeNotFoundError(LookupError): ...
class MigrationSchemaMissing(DatabaseError): ...
class CircularDependencyError(Exception): ...
class InconsistentMigrationHistory(Exception): ...Creating a simple migration:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(primary_key=True)),
('title', models.CharField(max_length=200)),
('content', models.TextField()),
('created_at', models.DateTimeField(auto_now_add=True)),
],
),
]Running custom Python code in migration:
def create_default_categories(apps, schema_editor):
Category = apps.get_model('myapp', 'Category')
Category.objects.bulk_create([
Category(name='Technology'),
Category(name='Science'),
])
class Migration(migrations.Migration):
operations = [
migrations.RunPython(create_default_categories),
]Install with Tessl CLI
npx tessl i tessl/pypi-django-stubs