import json
|
|
from django.core.management.base import BaseCommand
|
|
from lyrics.models import Cancion, Album
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Importa canciones desde un archivo JSON"
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument('archivo_json', type=str, help="Ruta del archivo JSON")
|
|
|
|
def handle(self, *args, **kwargs):
|
|
archivo_json = kwargs['archivo_json']
|
|
|
|
try:
|
|
with open(archivo_json, 'r', encoding='utf-8') as file:
|
|
datos = json.load(file)
|
|
|
|
self.stdout.write(self.style.WARNING(f"\nSe encontraron {len(datos)} canciones en el archivo '{archivo_json}'."))
|
|
confirmar = input("¿Deseas continuar con la importación? (s/n): ").strip().lower()
|
|
|
|
if confirmar != 's':
|
|
self.stdout.write(self.style.ERROR("Importación cancelada."))
|
|
return
|
|
|
|
canciones_creados = 0
|
|
for cancion_data in datos:
|
|
try:
|
|
album = Album.objects.get(id=cancion_data["album"])
|
|
|
|
creado = Cancion.objects.create(
|
|
album_id=album.id,
|
|
title=cancion_data['title'],
|
|
artist=cancion_data['artist'],
|
|
year=cancion_data['year'],
|
|
lyrics=cancion_data['lyrics'],
|
|
pista=cancion_data['pista'],
|
|
)
|
|
if creado:
|
|
canciones_creados += 1
|
|
|
|
except Album.DoesNotExist:
|
|
self.stderr.write(self.style.ERROR(f"Album '{cancion_data['album']}' no encontrado."))
|
|
|
|
self.stdout.write(self.style.SUCCESS(f'Se importaron {canciones_creados} canciones correctamente.'))
|
|
|
|
except FileNotFoundError:
|
|
self.stderr.write(self.style.ERROR(f"El archivo {archivo_json} no se encontró."))
|
|
except json.JSONDecodeError:
|
|
self.stderr.write(self.style.ERROR("Error al leer el archivo JSON. Asegúrate de que el formato sea correcto."))
|