Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add import command #77

Merged
merged 1 commit into from
Nov 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions backend/management/commands/import.py
Original file line number Diff line number Diff line change
@@ -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)