I’m having trouble with double entries in my django database and hope for your help. Let’s say I have two tables (person, car) which are joined via a many-to-many field. Each new entry inserts one person and, say, their three favourite cars. Each person is unique, the cars are not. Now, before adding a car I want to check if said car is already in the car table (i.e. someone else also likes it). If so, don’t add a new car entry, but link to the existing entry. This is what I have so far:
newPerson = project.models.Person.objects.create(…)
for i in range(len(cars)):
newCar = project.models.Car.objects.create(car=cars[i])
newPerson.cars.add(newCar)
How do I make sure no car is entered twice and person still points to the correct cars?
You could use get_or_create to insert only if the object doesnt exist.