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
apps: Dict[str, Dict[str, Type[tortoise.models.Model]]] = {}
async classmethod close_connections()

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.

Return type

None

classmethod describe_model(model, serializable=True)

Describes the given list of models or ALL registered models.

Parameters
  • model (Type[Model]) – The Model to describe

  • serializable (bool) – False if you want raw python objects, True for JSON-serialisable 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)

Describes the given list of models or ALL registered models.

Parameters
  • models (Optional[List[Type[Model]]]) – List of models to describe, if not provided then describes ALL registered models

  • serializable (bool) – 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)

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 (bool) – 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)

Returns the connection by name.

Raises

KeyError – If connection name does not exist.

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)

Sets up Tortoise-ORM.

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

Parameters
  • config (Optional[dict]) –

    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 (Optional[str]) – Path to .json or .yml (if PyYAML installed) file containing config with same format as above.

  • db_url (Optional[str]) – Use a DB_URL string. See DB_URL

  • modules (Optional[Dict[str, Iterable[Union[str, module]]]]) – Dictionary of key: [list_of_modules] that defined “apps” and modules that should be discovered for models.

  • _create_db (bool) – If True tries to create database for specified connections, could be used for testing purposes.

  • use_tz (bool) – A boolean that specifies if datetime will be timezone-aware by default or not.

  • timezone (str) – Timezone to use, default is UTC.

  • routers (Optional[List[Union[str, Type[type]]]]) – 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)

Early initialisation of Tortoise ORM Models.

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

Parameters
  • models_paths (Iterable[Union[str, module]]) – Models paths to initialise

  • app_label (str) – The app label, e.g. ‘models’

  • _init_relations (bool) – Whether to init relations or not

Raises

ConfigurationError – If models are invalid.

Return type

None

tortoise.run_async(coro)

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