Last active
February 15, 2018 22:58
-
-
Save darwing1210/c47933b0ee37333199689df34d50e695 to your computer and use it in GitHub Desktop.
Django Command to reset apps tables
This file contains 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 io import StringIO | |
from optparse import make_option | |
from django.apps import apps | |
from django.core.management.base import AppCommand, CommandError | |
from django.core.management.color import no_style | |
from django.core.management import call_command | |
from django.db import connections, transaction, DEFAULT_DB_ALIAS | |
class Command(AppCommand): | |
help = 'Reset app tables' | |
output_transaction = False | |
""" python manage.py flush_app core """ | |
def add_arguments(self, parser): | |
super(Command, self).add_arguments(parser) | |
parser.add_argument( | |
'--noinput', action='store_false', | |
dest='interactive', default=True, | |
help='Tells Django to NOT prompt the user for input of any kind.') | |
parser.add_argument( | |
'--database', action='store', dest='database', | |
default=DEFAULT_DB_ALIAS, help='Nominates a database to reset. ' | |
'Defaults to the "default" database.') | |
def handle_app_config(self, app_config, **options): | |
using = options.get('database') | |
connection = connections[using] | |
app_label = app_config.label | |
self.style = no_style() | |
if options.get('interactive'): | |
confirm = input(""" | |
You have requested a database reset. | |
This will IRREVERSIBLY DESTROY any data for | |
the "%s" application in the database "%s". | |
Are you sure you want to do this? | |
Type 'yes' to continue, or 'no' to cancel: """ % ( | |
app_label, connection.settings_dict['NAME'])) | |
else: | |
confirm = 'yes' | |
if confirm == 'yes': | |
try: | |
app_models = apps.get_app_config(app_label).get_models() | |
for model in app_models: | |
print('Deleting Data for model %s' % model) | |
model.objects.all().delete() | |
commands = StringIO() | |
cursor = connection.cursor() | |
call_command( | |
'sqlsequencereset', | |
app_label, | |
stdout=commands, no_color=True) | |
cursor.execute(commands.getvalue()) | |
except Exception as e: | |
raise CommandError( | |
"""Error: %s couldn't be reset. Possible reasons: | |
* The database isn't running or isn't configured correctly. | |
* At least one of the database tables doesn't exist. | |
* The SQL was invalid. | |
The full error: %s""" % (app_label, e)) | |
else: | |
print("Reset cancelled.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment