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

34 lines
1.4 KiB
Python

import os
import csv
from django.core.management.base import BaseCommand
from inventory.models import CarMake
class Command(BaseCommand):
help = "Update or add CarMake entries from a CSV file"
def handle(self, *args, **kwargs):
# Path to the car_make CSV file
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, "../../data/car_make.csv")
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:
car_make, created = CarMake.objects.get_or_create(
id_car_make=row['id_car_make'],
defaults={
'name': row['name'],
'arabic_name': row.get('arabic_name', ''),
'logo': row.get('logo', None),
'is_sa_import': row.get('is_sa_import', False) in ['1', 'True', 'true'],
},
)
if created:
self.stdout.write(self.style.SUCCESS(f"Added CarMake with ID {car_make.id_car_make}"))
else:
self.stdout.write(self.style.WARNING(f"CarMake with ID {car_make.id_car_make} already exists"))