import os import csv from django.core.management.base import BaseCommand from inventory.models import CarSerie, CarModel class Command(BaseCommand): help = "Update or add CarSerie entries from a merged CSV file" def handle(self, *args, **kwargs): # Path to the merged CSV file base_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join( base_dir, "../../data/Updated_Merged_Car_Generation_and_Serie_Data.csv" ) # Adjust the path if needed if not os.path.exists(file_path): self.stdout.write(self.style.ERROR(f"File not found: {file_path}")) return with open(file_path, newline="", encoding="utf-8") as csvfile: reader = csv.DictReader(csvfile) for row in reader: try: car_model = CarModel.objects.get(pk=row["id_car_model"]) except CarModel.DoesNotExist: self.stdout.write( self.style.WARNING( f"CarModel with ID {row['id_car_model']} not found" ) ) continue car_serie, created = CarSerie.objects.update_or_create( id_car_serie=row["id_car_serie"], defaults={ "id_car_model": car_model, "name": row["name"], "arabic_name": "-", "year_begin": int(float(row["year_begin"])) if row["year_begin"] else None, "year_end": int(float(row["year_end"])) if row["year_end"] else None, "generation_name": row["generation_name"], }, ) action = "Created" if created else "Updated" self.stdout.write( self.style.SUCCESS( f"{action} CarSerie with ID {car_serie.id_car_serie}" ) )