[Answered ]-Updating database based on previous csv file uploads – delete – create – or update Python/Dajngo

1πŸ‘

βœ…

Step 1

An empty list was created to compare with uploaded data:

imported_cars = []

Step 2

Created a filter of unique value (primary Key) and checked if it existed and used the method get to update items. Created car (item variable) to update or create ubject.

  if Cars.objects.filter(vin=vin).exists():
         car = Cars.objects.get(vin=vin)

Step 3

Used else statement to create item if it did not exist.

         else:
             car = Cars.objects.create(vin=vin, condition=condition...)

Last, out of the loop populated empty list with updated and created cars and deleted items that were in the database but not in the csv file.

    imported_cars_vin_numbers = [car.vin for car in imported_cars]
    for car in Cars.objects.all():
        if car.vin not in imported_cars_vin_numbers:
            car.delete()

Special thanks and credit to Zack PlauchΓ© who was extremely helpful and professional in helping me and teaching me how to solve this issue.

πŸ‘€Pablo Espinal

0πŸ‘

Your issue is in the model.py

you should write the Cars object with the following.

vin = models.CharField(primary_key=True, editable=False)

Confirm this works, since I am suggesting solution without actually seeing the model.py

This should handle the update aspect of your logic. The part where you delete a vin if its not in the CSV will have to be done with new process I don’t see written here.But a suggestion would be to clear the DB and repopulate, or create function that compares DB with CSV and delete object if not in CSV.

πŸ‘€MoLoW

Leave a comment