Django ORM doesn't save value when referencing to them by child attributes

51 views Asked by At

Today I found something very tricky. I use django 1.7.7 (if this is important).

I have two models in relation: Car and Driver. I want to connect with each other instances of car object and driver object. Both objects seems(*) to be already created.

In both cases:

car = Car.objects.create()
car.save()
driver = Driver.objects.create()
driver.save()

self.garage.car = car
self.garage.save()

and next:

# doesn't work
self.garage.car.driver = driver
self.garage.car.save()
# self.object.car.driver is None

but:

# works
car = self.garage.car
car.driver = driver
car.save()
# self.object.car.driver is driver

(*) - To be honest I am not sure, whether these objects are fully created or not yet. Everything is going on in View, both objects have already own ids, however manual query to database shows, that those objects are not yet present. Transaction is not finished?

1

There are 1 answers

1
Paweł Gruszka On BEST ANSWER

Because in your sample code, first self.object.car is not the same object you save in the line below. Check this out:

self.garage.car is self.garage.car

If above is False the only explanation is that car is a property and you get new instance of object every time you call this property.