med/media/management/commands/regenerate_side_identifiers.py

69 lines
2.9 KiB
Python

from django.core.management import BaseCommand
from django.db import transaction
from media.forms import generate_side_identifier
from media.models import BD, Manga, Roman
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--type', '-t',
type=str,
default='bd',
choices=['bd', 'manga', 'roman'],
help="Type of medium where the "
"sides need to be regenerated.")
parser.add_argument('--noninteractivemode', '-ni', action="store_true",
help="Disable the interaction mode and replace "
"existing side identifiers.")
parser.add_argument('--no-commit', '-nc', action="store_true",
help="Only show modifications, don't commit "
"them to database.")
@transaction.atomic
def handle(self, *args, **options):
t = options["type"]
medium_class = None
if t == "bd":
medium_class = BD
elif t == "manga":
medium_class = Manga
elif t == "roman":
medium_class = Roman
interactive_mode = not options["noninteractivemode"]
replaced = 0
for obj in medium_class.objects.all():
current_side_identifier = obj.side_identifier
if not obj.authors.all():
self.stdout.write(str(obj))
subtitle = obj.subtitle if hasattr(obj, "subtitle") else None
generated_side_identifier = generate_side_identifier(
obj.title, obj.authors.all(), subtitle)
if current_side_identifier != generated_side_identifier:
answer = 'y'
if interactive_mode:
answer = ''
while answer != 'y' and answer != 'n':
answer = input(f"For medium {obj}, current side: "
f"{current_side_identifier}, "
f"generated side: "
f"{generated_side_identifier}, "
f"would you like to replace ? [y/n]")\
.lower()[0]
if answer == 'y':
self.stdout.write(self.style.WARNING(
f"Replace side of {obj} from {current_side_identifier}"
f" to {generated_side_identifier}..."))
obj.side_identifier = generated_side_identifier
if not options["no_commit"]:
obj.save()
replaced += 1
if replaced:
self.stdout.write(self.style.SUCCESS(
f"{replaced} side identifiers were replaced."))
else:
self.stdout.write(self.style.WARNING("Nothing changed."))