How to TRUNCATE TABLE using Django's ORM?

后端 未结 8 1005
别跟我提以往
别跟我提以往 2020-12-15 15:28

To empty a database table, I use this SQL Query:

TRUNCATE TABLE `books`

How to I truncate a table using Django\'s models and ORM?

I

8条回答
  •  半阙折子戏
    2020-12-15 16:29

    For me the to truncate my local sqllite database I end up with python manage.py flush.

    What I have initial tried is to iterate over the models and delete all to rows one by one:

    models = [m for c in apps.get_app_configs() for m in c.get_models(include_auto_created=False)]
    
            for m in models:
                m.objects.all().delete()
    

    But becuse I have Protected foreign key the success of the operation depended on the order of the models.

    So, I am using te flush command to truncate my local test database and it is working for me https://docs.djangoproject.com/en/3.0/ref/django-admin/#django-admin-flush

提交回复
热议问题