How to prevent overwriting an object someone else has modified

孤街醉人 提交于 2019-12-21 21:37:50

问题


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.


回答1:


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()


来源:https://stackoverflow.com/questions/467134/how-to-prevent-overwriting-an-object-someone-else-has-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!