import json
|
|
from django.core.management.base import BaseCommand
|
|
from repostajes.models import Repostaje, Vehiculo
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Importa repostajes 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)} repostajes 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
|
|
|
|
repostajes_creados = 0
|
|
for repostaje_data in datos:
|
|
try:
|
|
vehiculo = Vehiculo.objects.get(id=repostaje_data["vehiculo"])
|
|
|
|
creado = Repostaje.objects.create(
|
|
vehiculo_id=vehiculo.id,
|
|
fecha=repostaje_data['fecha'],
|
|
kms=repostaje_data['kms'],
|
|
litros=repostaje_data['litros'],
|
|
descuento=repostaje_data['descuento'],
|
|
importe=repostaje_data['importe'],
|
|
precioxlitro=repostaje_data['precioxlitro'],
|
|
kmsrecorridos=repostaje_data['kmsrecorridos'],
|
|
consumo=repostaje_data['consumo']
|
|
)
|
|
if creado:
|
|
repostajes_creados += 1
|
|
|
|
except Vehiculo.DoesNotExist:
|
|
self.stderr.write(self.style.ERROR(f"Vehiculo '{repostaje_data['vehiculo']}' no encontrado."))
|
|
|
|
self.stdout.write(self.style.SUCCESS(f'Se importaron {repostajes_creados} repostajes 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."))
|