tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.68k stars 390 forks source link

How to use truncate table elegantly? #1392

Closed dyuzhou closed 8 months ago

dyuzhou commented 1 year ago

I need the operation to truncate the table, I can't find it in the documentation

I found related method in django

1.

await UserModel.all().delete()

2.

await Tortoise.get_connection("default").execute_query("TRUNCATE TABLE table_name;")

3.

from typing import Optional

from tortoise.models import Model
from tortoise import BaseDBAsyncClient

class MyBaseModel(Model):

    @classmethod
    async def truncate_model(cls, using_db: Optional[BaseDBAsyncClient] = None):
        db = using_db or cls._choose_db(True)
        return await db.execute_query('TRUNCATE TABLE {}'.format(cls._meta.db_table))

The third way seems to solve my problem elegantly, wondering if this functionality can be built in? or he has some safety hazard?

long2ice commented 1 year ago

No, just execute raw sql