Last active
February 22, 2019 14:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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