From 999262baa8b840fbcff86f777c839496eacb7581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20H=C3=A1la?= Date: Sat, 25 Nov 2023 17:21:07 +0100 Subject: [PATCH] Add import command --- backend/management/commands/import.py | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 backend/management/commands/import.py diff --git a/backend/management/commands/import.py b/backend/management/commands/import.py new file mode 100644 index 0000000..6af5790 --- /dev/null +++ b/backend/management/commands/import.py @@ -0,0 +1,41 @@ +"""Management command for importing Songs""" +import json +import logging +from argparse import ArgumentParser +from pathlib import Path + +from django.core.management import BaseCommand +from django.db import transaction + +from backend.models import Song +from category.models import Category + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +class Command(BaseCommand): + """Imports Songs from a JSON""" + + help = "Imports Songs from JSON" + + def add_arguments(self, parser: ArgumentParser): + parser.add_argument( + "-c", + "--category", + required=True, + type=int, + help="ID of a target category", + ) + parser.add_argument("input", type=Path, help="Input JSON file") + + def handle(self, *args, **options): + category = Category.objects.get(id=options["category"]) + + with open(options["input"], encoding="UTF-8") as file: + imported = json.load(file) + + with transaction.atomic(): + songs = Song.objects.bulk_create(Song(**song) for song in imported) + for song in songs: + song.categories.add(category)