tortoise-orm

How to run simple scripts using tortoise-orm?


How to run simple scripts that connect db and execute a query in tortoise-orm?


Solution

  • If you are running a simple script, you can do 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 (run this only if you need to generate the schema)
        # await Tortoise.generate_schemas()
    
    run_async(init())
    

    run_async is a helper function to run simple async Tortoise scripts. If you are running Tortoise ORM as part of a service, please have a look at The Importance of cleaning up properly from tortoise orm docs.