2

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.

muhuk
  • 15,777
  • 9
  • 59
  • 98
  • You want to prevent yourself from doing something? Why just not save it twice? – nosklo Jan 21 '09 at 21:48
  • Look here: http://stackoverflow.com/questions/320096/django-how-can-i-protect-against-concurrent-modification-of-data-base-entries – tvanfosson Jan 21 '09 at 22:07
  • @nosklo: a web application is typically multi-user, so I'm not necessarily preventing myself. I want to prevent saving on someone else's modifications without noticing. – muhuk Jan 21 '09 at 22:08

1 Answers1

3

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()
Sergey Golovchenko
  • 18,203
  • 15
  • 55
  • 72
  • 1
    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 Jan 30 '10 at 00:16
  • Beware, this answer is not correct for the reason Andrei stated above!! It will land you in serious trouble if you use it in production. See this question for more info: http://stackoverflow.com/questions/320096/django-how-can-i-protect-against-concurrent-modification-of-database-entries – Nick Sweeting Aug 03 '16 at 20:41