haikal/inventory/management/commands/add_id_car_model.py
2025-06-22 13:25:54 +03:00

77 lines
3.0 KiB
Python

import csv
import os
from django.core.management.base import BaseCommand
from django.db import connection
from inventory.models import CarTrim
class Command(BaseCommand):
help = "Add id_car_model column to CarTrim model and populate it using a CSV file."
def handle(self, *args, **options):
# Define the file path relative to the project directory
base_dir = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
file_path = os.path.join(base_dir, "data/mappings.csv")
# Step 1: Add the new column if it does not exist
with connection.cursor() as cursor:
try:
cursor.execute(
"ALTER TABLE inventory_cartrim ADD COLUMN id_car_model INTEGER"
)
self.stdout.write(
self.style.SUCCESS("Column 'id_car_model' added successfully.")
)
except Exception as e:
self.stdout.write(
self.style.WARNING(
f"Column 'id_car_model' might already exist: {e}"
)
)
# Step 2: Read and process the CSV file
try:
with open(file_path, mode="r", encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Extract id_car_serie and id_car_model from the current row
id_car_serie = row.get("id_car_serie")
id_car_model = row.get("id_car_model")
if not id_car_serie or not id_car_model:
self.stdout.write(
self.style.WARNING(f"Skipping row with missing data: {row}")
)
continue
# Step 3: Update CarTrim rows based on the id_car_serie
updated_count = CarTrim.objects.filter(
id_car_serie=id_car_serie
).update(id_car_model=id_car_model)
# Output progress
if updated_count > 0:
self.stdout.write(
self.style.SUCCESS(
f"Updated {updated_count} rows for id_car_serie={id_car_serie} with id_car_model={id_car_model}."
)
)
else:
self.stdout.write(
self.style.WARNING(
f"No rows found for id_car_serie={id_car_serie}."
)
)
self.stdout.write(
self.style.SUCCESS("All rows have been processed successfully!")
)
except FileNotFoundError:
self.stdout.write(self.style.ERROR(f"File not found: {file_path}"))
except Exception as e:
self.stdout.write(self.style.ERROR(f"An error occurred: {e}"))