mysqlormforeign-keystortoise-orm

Tortoise ORM: how to disable foreign key checks temporarily?


In raw MySQL it's easy to disable foreign key checks temporarily while you're doing migrations etc.

SET foreign_key_checks = 0;

My team uses Tortoise ORM and we need to replicate that functionality. How can we do that?

Google and Stack Overflow searches have yielded nothing.

Migrations generated by Tortoise ORM fail when a FK constraint needs to be ignored.


Solution

  • Unfortunately this feature is not supported in Tortoise ORM, however, you can use the method execute_query from the BaseDBAsyncClient class to execute RAW queries.

    e.g:

    from tortoise import Tortoise, run_async, connection
    
    async def run_raw_sql():
        await Tortoise.init(config=YOUR_CONNECTION_OBJ)
        conn = connection.connections.get("YOUR_CONNECTION_NAME")
        script = """
        SET foreign_key_checks = 0;
        ...
        ...
        """
        await conn.execute_script(script)
    
    
    # run_async is a helper function to run simple async Tortoise scripts.
    run_async(run_raw_sql())