mybuddy/babybuddy/management/commands/reset.py

76 lines
2.4 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
from os import path
from django.apps import apps
from django.contrib.auth import get_user_model
2020-01-29 05:55:54 +00:00
from django.core.cache import cache
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.core.management.commands.flush import Command as Flush
from .fake import Command as Fake
2020-01-29 04:45:37 +00:00
from .migrate import Command as Migrate
class Command(BaseCommand):
2022-02-10 00:00:30 +00:00
help = "Reapplies core migrations and generates fake data."
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.UserModel = get_user_model()
self.username_field = self.UserModel._meta.get_field(
2022-02-10 00:00:30 +00:00
self.UserModel.USERNAME_FIELD
)
# Disable system checks for reset.
self.requires_system_checks = False
def add_arguments(self, parser):
Migrate().add_arguments(parser)
Fake().add_arguments(parser)
def handle(self, *args, **options):
2022-02-10 00:00:30 +00:00
verbosity = options["verbosity"]
# Flush all existing database records.
flush = Flush()
flush.handle(**options)
if verbosity > 0:
2022-02-10 00:00:30 +00:00
self.stdout.write(self.style.SUCCESS("Database flushed."))
# Run migrations for all Baby Buddy apps.
for config in apps.app_configs.values():
2022-02-10 00:00:30 +00:00
if path.split(path.split(config.path)[0])[1] == "babybuddy":
migrate = Migrate()
2022-02-10 00:00:30 +00:00
options["app_label"] = config.name
options["migration_name"] = "zero"
try:
migrate.handle(*args, **options)
except CommandError:
# Ignore apps without migrations.
pass
# Run other migrations.
migrate = Migrate()
2022-02-10 00:00:30 +00:00
options["app_label"] = None
options["migration_name"] = None
migrate.handle(*args, **options)
# Create cache table.
call_command("createcachetable")
if verbosity > 0:
self.stdout.write(self.style.SUCCESS("Cache table created."))
2020-01-29 05:55:54 +00:00
# Clear cache.
cache.clear()
if verbosity > 0:
2022-02-10 00:00:30 +00:00
self.stdout.write(self.style.SUCCESS("Cache cleared."))
2020-01-29 05:55:54 +00:00
2020-01-29 04:45:37 +00:00
# Populate database with fake data.
fake = Fake()
fake.handle(*args, **options)
if verbosity > 0:
2022-02-10 00:00:30 +00:00
self.stdout.write(self.style.SUCCESS("Database reset complete."))