from django.core.management.base import BaseCommand from inventory.models import CarMake import json class Command(BaseCommand): help = "Update CarMake model with data from a JSON file" def handle(self, *args, **kwargs): # Load the JSON data from the file with open("carmake_updated_backup.json", "r", encoding="utf-8") as file: car_makes_data = json.load(file) # Iterate over the data and update the CarMake model for car_make_data in car_makes_data: pk = car_make_data["pk"] fields = car_make_data["fields"] # Get or create the CarMake instance car_make, created = CarMake.objects.get_or_create(pk=pk) # Update the fields car_make.name = fields["name"] car_make.arabic_name = fields["arabic_name"] car_make.logo = fields["logo"] car_make.is_sa_import = fields["is_sa_import"] # Save the updated instance car_make.save() if created: self.stdout.write( self.style.SUCCESS(f"Created CarMake: {car_make.name}") ) else: self.stdout.write( self.style.SUCCESS(f"Updated CarMake: {car_make.name}") )