aerich migration package for Tortoise ORM

Aerich a migration module for Tortoise ORM

Async programming is getting more popular with Python in recent years. From Python 3.4, we have native async support. Currently, there are not many ORMs (Object Relation Mappers) that support async. One such notable ORM is Tortoise ORM. But it does not not supports migration feature.

aerich package adds migrations support to Tortoise ORM. It works well with MySQL. I am yet to test with SQLite and PostgreSQL, will check and post findings.

We need Tortoise ORM version > 16.2 or above for aerich.

How it works

aerich maintains old_models.py file to which keeps tracks of last changes. Old models and current models compared, and if there are changes, respective SQL commands will be for upgrading and reverting.

aerich can be installed through pip

pip install aerich

Configuring aerich in the application pretty easy. we need to configure the TortoiseORM models.

  • We need to add "aerich.models" in Tortoise ORM configuration dict. It will create a table called aerich to capture the history of migrations.

    TORTOISE_ORM = { "connections": { "default": "mysql://user:test_pwd@localhost:3306/communication?charset=utf8mb4" }, "apps": { "models": { "models": ["app.models", "aerich.models"], "default_connection": "default", }, } }
  • We can initiate aerich with the below command and it will initiate migrations for the application.

    aerich init -t settings.TORTOISE_ORM
    • aerich.ini - config file maintains aerich configurations.
    • migrations folder - to capture all migrations.
  • To create initial migration files, the below creates initial migrations if not exists.

    aerich init-db
    • It creates JSON file with timestamp with initial SQL commands and
    • old_models.py - keeps tracks last applied changes.

The module provides the following commands.

  • migrate - compares the current models with old models and creates SQL query commands.
  • upgrade - applies all unapplied migrations to the database.
  • downgrade - reverts the last applied migrations.
  • history - lists all applied migrations.
  • heads - list unapplied migrations

to clear all migrations,

  • truncate the aerich table
  • remove models folder under migrations.

aerich is a promising module for tortoise ORM.


  • Python
  • aerich
  • Tortoise ORM
  • async

Published 9 months ago

Developed by Kamalakannan © 2020