How to TRUNCATE TABLE using Django's ORM?

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

    You can do this in a fast and lightweight way, but not using Django's ORM. You may execute raw SQL with a Django connection cursor:

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("TRUNCATE TABLE `books`")
    
    0 讨论(0)
  • 2020-12-15 16:07

    Now there's a library to help you truncate a specific TABLE in your Django project Database, It called django-truncate.

    It's simple just run python manage.py truncate --apps myapp --models Model1 and all of the data in that TABLE will be deleted!

    Learn more about it here: https://github.com/KhaledElAnsari/django-truncate

    0 讨论(0)
  • 2020-12-15 16:16

    This is doesn't directly answer the OP's question, but is nevertheless a solution one might use to achieve the same thing - differently.


    Well, for some strange reason (while attempting to use the suggested RAW methods in the other answers here), I failed to truncate my Django database cache table until I did something like this:

    import commands
    cmd = ['psql', DATABASE, 'postgres', '-c', '"TRUNCATE %s;"' % TABLE]
    commands.getstatusoutput(' '.join(cmd))
    

    Basically, I had to resort to issuing the truncate command via the database's utility commands - psql in this case since am using Postgres. So, automating the command line might handle such corner cases.

    Might save someone else some time...

    0 讨论(0)
  • 2020-12-15 16:17

    The closest you'll get with the ORM is Book.objects.all().delete().

    There are differences though: truncate will likely be faster, but the ORM will also chase down foreign key references and delete objects in other tables.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 16:23

    You can use the model's _meta property to fill in the database table name:

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute('TRUNCATE TABLE "{0}"'.format(MyModel._meta.db_table))
    

    Important: This does not work for inherited models as they span multiple tables!

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