Login

fast table flush without raw SQL

Author:
dsblank
Posted:
December 21, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

Perhaps you don't want to drop a table, but you also want to do something faster than Model.objects.all().delete() but without resorting to raw SQL. This function, clear_tables, will call the sql_flush operation on a list of tables.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def no_style():
    """Returns a Django Style object that has no colors."""
    class dummy(object):
        def __getattr__(self, attr):
            return lambda x: x
    return dummy()

def clear_tables(*flush_tables):
    from django.db import connection, transaction
    cursor = connection.cursor()
    statements = connection.ops.sql_flush(no_style(), 
                                          flush_tables, 
                                          connection.introspection.sequence_list())
    for statement in statements:
        cursor.execute(statement)
        transaction.commit_unless_managed()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

andyfoundi (on October 21, 2015):

I almost run the command above and reset ALL sequence of my tables, including the ones that I don't specify in the flush_tables, due to #13.

Here is my modified code for #13

reset_sequence = [ seq for seq in connection.introspection.sequence_list() if seq['table'] in flush_tables] statements = connection.ops.sql_flush(no_style(), flush_tables, connection.introspection.sequence_list())

#

Please login first before commenting.