Skip to content

Instantly share code, notes, and snippets.

@bencleary
Last active February 22, 2019 14:10
Show Gist options
  • Save bencleary/a2bab667ab2f602b3d7e12ac57ad3a88 to your computer and use it in GitHub Desktop.
Save bencleary/a2bab667ab2f602b3d7e12ac57ad3a88 to your computer and use it in GitHub Desktop.
A quick handy tool to truncate tables without using SQL but could be changed to execute SQL code, tracks progress and allows you to use an --app argument to delete data from all models given an app name. requires Django >= 1.11, tqdm
from django.core.management.base import BaseCommand
from django.apps import apps
from tqdm import tqdm
class Command(BaseCommand):
help = 'Drops table data from a specified app name'
def add_arguments(self, parser):
parser.add_argument('--app', type=str, help='The app name you wish to truncate the data from all models!')
def handle(self, *args, **kwargs):
app_name = kwargs['app']
app_instance = apps.get_app_config(app_name)
for model in app_instance.get_models():
print(f"--> 🎫 Model Instance {model.__name__}")
item_count = model.objects.all().count()
print(f"--> πŸ—„ Current Record Count: {item_count}")
progress_bar = tqdm(desc=f"--> πŸ—‘ Deleting Records!", ncols=70, total=item_count)
for obj in model.objects.all():
progress_bar.update(1)
obj.delete()
progress_bar.close()
print(f"--> 🧨 All Items Deleted")
item_count = model.objects.all().count()
print(f"--> πŸ—„ New Record Count: {item_count}")
from django.core.management.base import BaseCommand
from django.apps import apps
from django.db import connection
from django.db.utils import OperationalError
class Command(BaseCommand):
help = 'Drops table data from a specified app name'
def add_arguments(self, parser):
parser.add_argument('--app', type=str, help='The app name you wish to drop the tables & data from all models!')
def handle(self, *args, **kwargs):
app_name = kwargs['app']
app_instance = apps.get_app_config(app_name)
for model in app_instance.get_models():
try:
print(f"--> 🎫 Model Instance {model.__name__}")
item_count = model.objects.all().count()
print(f"--> πŸ—„ Current Record Count: {item_count}")
with connection.cursor() as cursor:
table_name = model._meta.db_table
sql = f"DROP TABLE {table_name};"
cursor.execute(sql)
print(f"--> 🧨 Table Dropped")
except (model.DoesNotExist, OperationalError):
print("--> πŸ”Ž Table Not Found, Migrations Run?")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment