views:

208

answers:

1

I would like to find a generic way of preventing to save an object if it is saved after I checked it out.

We can assume the object has a timestamp field that contains last modification time. If I had checked out (visited a view using a ModelForm for instance) at t1 and the object is saved again at t2, given t2 > t1 I shouldn't be able to save it.

+3  A: 

Overwrite the save method that would first check the last timestamp:

def save(self):
    if(self.id):
        foo = Foo.objects.get(pk=self.id)
        if(foo.timestamp > self.timestamp):
            raise Exception, "trying to save outdated Foo" 
    super(Foo, self).save()
a race condition can occur between the timestamp if check and the sql update query. the condition should be part of the update query which is atomic.
Andrei Savu