Set up

Init app

After you defined all your models, tortoise needs you to init them, in order to create backward relations between models and match your db client with appropriate models.

You can do it like this:

from tortoise import Tortoise

async def init():
    # Here we create a SQLite DB using file "db.sqlite3"
    #  also specify the app name of "models"
    #  which contain models from "app.models"
    await Tortoise.init(
        db_url='sqlite://db.sqlite3',
        modules={'models': ['app.models']}
    )
    # Generate the schema
    await Tortoise.generate_schemas()

Here we create connection to SQLite database client and then we discover & initialize models.

generate_schema generates schema on empty database, you shouldn’t run it on every app init, run it just once, maybe out of your main code. There is also the option when generating the schemas to set the safe parameter to True which will only insert the tables if they don’t already exist.

If you define the variable __models__ in the app.models module (or wherever you specify to load your models from), generate_schema will use that list, rather than automatically finding models for you.

The Importance of cleaning up

Tortoise ORM will keep connections open to external Databases. As an asyncio Python library, it needs to have the connections closed properly or the Python interpreter may still wait for the completion of said connections.

To ensure connections are closed please ensure that Tortoise.close_connections() is called:

await Tortoise.close_connections()

The small helper function tortoise.run_async() will ensure that connections are closed.

Reference

class tortoise.Tortoise[source]
apps : dict[str, dict[str, type[Model]]] = {}
async classmethod close_connections()[source]

Close all connections cleanly.

It is required for this to be called on exit, else your event loop may never complete as it is waiting for the connections to die.

Warning

This is deprecated and will be removed in a future release. Please use connections.close_all instead.

Return type:

None

classmethod describe_model(model, serializable=True)[source]

Describes the given list of models or ALL registered models.

Parameters:
model

The Model to describe

serializable=True

False if you want raw python objects, True for JSON-serializable data. (Defaults to True)

See tortoise.models.Model.describe()

Warning

This is deprecated, please use tortoise.models.Model.describe() instead

Return type:

dict

classmethod describe_models(models=None, serializable=True)[source]

Describes the given list of models or ALL registered models.

Parameters:
models=None

List of models to describe, if not provided then describes ALL registered models

serializable=True

False if you want raw python objects, True for JSON-serializable data. (Defaults to True)

Return type:

Dict[str, dict]

Returns:

A dictionary containing the model qualifier as key, and the same output as describe_model(...) as value:

{
    "models.User": {...},
    "models.Permission": {...}
}

async classmethod generate_schemas(safe=True)[source]

Generate schemas according to models provided to .init() method. Will fail if schemas already exists, so it’s not recommended to be used as part of application workflow

Parameters:
safe=True

When set to true, creates the table only when it does not already exist.

Raises:

ConfigurationError – When .init() has not been called.

Return type:

None

classmethod get_connection(connection_name)[source]

Returns the connection by name.

Raises:

ConfigurationError – If connection name does not exist.

Warning

This is deprecated and will be removed in a future release. Please use connections.get instead.

Return type:

BaseDBAsyncClient

async classmethod init(config=None, config_file=None, _create_db=False, db_url=None, modules=None, use_tz=False, timezone='UTC', routers=None)[source]

Sets up Tortoise-ORM.

You can configure using only one of config, config_file and (db_url, modules).

Parameters:
config=None

Dict containing config:

Example

{
    'connections': {
        # Dict format for connection
        'default': {
            'engine': 'tortoise.backends.asyncpg',
            'credentials': {
                'host': 'localhost',
                'port': '5432',
                'user': 'tortoise',
                'password': 'qwerty123',
                'database': 'test',
            }
        },
        # Using a DB_URL string
        'default': 'postgres://postgres:qwerty123@localhost:5432/test'
    },
    'apps': {
        'my_app': {
            'models': ['__main__'],
            # If no default_connection specified, defaults to 'default'
            'default_connection': 'default',
        }
    },
    'routers': ['path.router1', 'path.router2'],
    'use_tz': False,
    'timezone': 'UTC'
}

config_file=None

Path to .json or .yml (if PyYAML installed) file containing config with same format as above.

db_url=None

Use a DB_URL string. See DB_URL

modules=None

Dictionary of key: [list_of_modules] that defined “apps” and modules that should be discovered for models.

_create_db=False

If True tries to create database for specified connections, could be used for testing purposes.

use_tz=False

A boolean that specifies if datetime will be timezone-aware by default or not.

timezone='UTC'

Timezone to use, default is UTC.

routers=None

A list of db routers str path or module.

Raises:

ConfigurationError – For any configuration error

Return type:

None

classmethod init_models(models_paths, app_label, _init_relations=True)[source]

Early initialisation of Tortoise ORM Models.

Initialise the relationships between Models. This does not initialise any database connection.

Parameters:
models_paths

Models paths to initialise

app_label

The app label, e.g. ‘models’

_init_relations=True

Whether to init relations or not

Raises:

ConfigurationError – If models are invalid.

Return type:

None

tortoise.run_async(coro)[source]

Simple async runner that cleans up DB connections on exit. This is meant for simple scripts.

Usage:

from tortoise import Tortoise, run_async

async def do_stuff():
    await Tortoise.init(
        db_url='sqlite://db.sqlite3',
        models={'models': ['app.models']}
    )

    ...

run_async(do_stuff())
Return type:

None