How to TRUNCATE TABLE using Django's ORM?

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

    In addition to Ned Batchelder's answer and refering to Bernhard Kircher's comment:

    In my case I needed to empty a very large database using the webapp:

    Book.objects.all().delete()
    

    Which, in the development SQLlite environment, returned:

    too many SQL variables
    

    So I added a little workaround. It maybe not the neatest, but at least it works until the truncate table option is build into Django's ORM:

    countdata = Book.objects.all().count()
    logger.debug("Before deleting: %s data records" % countdata)
    while countdata > 0:
        if countdata > 999:
            objects_to_keep = Book.objects.all()[999:]
            Book.objects.all().exclude(pk__in=objects_to_keep).delete()
            countdata = Book.objects.all().count()
        else:
            Book.objects.all().delete()
            countdata = Book.objects.all().count()
    

    By the way, some of my code was based on "Django Delete all but last five of queryset".

    I added this while being aware the answer was already answered, but hopefully this addition will help some other people.

提交回复
热议问题