How to TRUNCATE TABLE using Django's ORM?

后端 未结 8 965
别跟我提以往
别跟我提以往 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:28

    I know this is a very old Question and few corrects answer is in here is as well but I can't resist myself to share the most elegant and fastest way to serve the purpose of this question.

    class Book(models.Model):
        # Your Model Declaration
    
        @classmethod
        def truncate(cls):
            with connection.cursor() as cursor:
                cursor.execute('TRUNCATE TABLE {} CASCADE'.format(cls._meta.db_table))
    

    And now to truncate all data from Book table just call

    Book.truncate()
    

    Since this is directly interact with your Database it will perform much faster than doing this

    Book.objects.all().delete()
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题