64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
import os
|
|
import csv
|
|
from django.core.management.base import BaseCommand
|
|
from inventory.models import CarSpecificationValue, CarSpecification, CarTrim
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = "Update or add CarSpecificationValue entries from a CSV file"
|
|
|
|
def handle(self, *args, **kwargs):
|
|
# Path to the car_specification_value CSV file
|
|
base_dir = os.path.dirname(os.path.abspath(__file__))
|
|
file_path = os.path.join(
|
|
base_dir, "../../data/car_specification_value.csv"
|
|
) # Adjust this 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_trim = CarTrim.objects.get(pk=row["id_car_trim"])
|
|
except CarTrim.DoesNotExist:
|
|
self.stdout.write(
|
|
self.style.WARNING(
|
|
f"CarTrim with ID {row['id_car_trim']} not found"
|
|
)
|
|
)
|
|
continue
|
|
|
|
try:
|
|
car_specification = CarSpecification.objects.get(
|
|
pk=row["id_car_specification"]
|
|
)
|
|
except CarSpecification.DoesNotExist:
|
|
self.stdout.write(
|
|
self.style.WARNING(
|
|
f"CarSpecification with ID {row['id_car_specification']} not found"
|
|
)
|
|
)
|
|
continue
|
|
|
|
car_specification_value, created = (
|
|
CarSpecificationValue.objects.update_or_create(
|
|
id_car_specification_value=row["id_car_specification_value"],
|
|
defaults={
|
|
"id_car_trim": car_trim,
|
|
"id_car_specification": car_specification,
|
|
"value": row["value"],
|
|
"unit": row.get("unit", ""),
|
|
},
|
|
)
|
|
)
|
|
|
|
action = "Created" if created else "Updated"
|
|
self.stdout.write(
|
|
self.style.SUCCESS(
|
|
f"{action} CarSpecificationValue with ID {car_specification_value.id_car_specification_value}"
|
|
)
|
|
)
|