haikal/inventory/management/commands/update_car_trim.py
2024-12-17 16:29:10 +03:00

47 lines
2.2 KiB
Python

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