Aerich
Aerich is a database migrations tool specifically designed for Tortoise ORM. It automates schema evolution by generating and applying migration scripts, making it easier to manage database changes in Python projects. It is actively maintained, with version 0.9.2 being the latest as of early 2024, and features regular releases for bug fixes and new functionality.
Common errors
-
No Tortoise-ORM config found. Please specify it via --tortoise-config or environment variable AERICH_CONFIG
cause Aerich could not locate your Tortoise-ORM configuration. The `AERICH_CONFIG` environment variable is deprecated/removed in newer versions.fixProvide the configuration path directly using the `-t` or `--tortoise-config` argument: `aerich init -t your_app.config.TORTOISE_CONFIG`. -
tortoise.exceptions.ConfigurationError: app models has no default connection
cause One of the apps defined in your `TORTOISE_CONFIG['apps']` dictionary is missing the `default_connection` key, or its value is invalid.fixEnsure each app configuration in `TORTOISE_CONFIG['apps']` correctly specifies its default connection, e.g., `"default_connection": "default"`. -
tortoise.exceptions.OperationalError: no such table: aerich
cause Aerich's internal migration table (`aerich`) was not created. This usually happens if `aerich.models` is not included in `TORTOISE_CONFIG` or if `aerich initdb` (or `aerich init` then `aerich upgrade`) was not run.fix1. Ensure `'aerich.models'` is in your `TORTOISE_CONFIG['apps']['models']['models']`. 2. Run `aerich init -t your_config.TORTOISE_CONFIG` followed by `aerich upgrade`.
Warnings
- breaking Aerich versions 0.6.0 and later removed the `AERICH_CONFIG` environment variable and changed how Tortoise-ORM configuration is specified.
- gotcha Failing to include `aerich.models` in your `TORTOISE_CONFIG['apps']['models']['models']` list will prevent Aerich from managing its internal schema and lead to errors.
- gotcha Using `sqlite://:memory:` in your `TORTOISE_CONFIG` for database connections will result in database changes (including migrations) not being persisted.
Install
-
pip install aerich
Imports
- AerichCommand
from aerich.commands import AerichCommand
Quickstart
# config.py
from tortoise import fields, models
class User(models.Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
class Meta:
table = "users"
TORTOISE_CONFIG = {
"connections": {"default": "sqlite://db.sqlite3"},
"apps": {
"models": {
"models": ["config", "aerich.models"], # "config" refers to models defined in this file
"default_connection": "default",
}
},
}