import os import csv from django.core.management.base import BaseCommand from inventory.models import CarModel, CarMake class Command(BaseCommand): help = "Update or add CarModel entries from a CSV file" def handle(self, *args, **kwargs): # Path to the car_model CSV file base_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join( base_dir, "../../data/car_model.csv" ) # Adjust 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_make = CarMake.objects.get(pk=row["id_car_make"]) except CarMake.DoesNotExist: self.stdout.write( self.style.WARNING( f"CarMake with ID {row['id_car_make']} not found" ) ) continue car_model, created = CarModel.objects.update_or_create( id_car_model=row["id_car_model"], defaults={ "id_car_make": car_make, "name": row["name"], "arabic_name": row.get("arabic_name", ""), }, ) action = "Created" if created else "Updated" self.stdout.write( self.style.SUCCESS( f"{action} CarModel with ID {car_model.id_car_model}" ) )