Login

fast table flush without raw SQL

Author:
dsblank
Posted:
December 21, 2009
Language:
Python
Version:
1.1
Tags:
delete flush fast
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. oneliner to delete SQLite tables by kifkif 5 years, 10 months ago
  2. Load customized SQL by roppert 6 years, 6 months ago
  3. custom sql without table names by robharvey 8 years, 3 months ago
  4. grep and delete sqlite tables by kifkif 5 years, 9 months ago
  5. Table Creation Using ORM Standalone by EliAndrewC 7 years, 6 months ago

Comments

Please login first before commenting.