如何防止覆盖别人修改的对象 [英] How to prevent overwriting an object someone else has modified

查看:94
本文介绍了如何防止覆盖别人修改的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种通用的方法来防止保存一个对象,如果它在保存后我检查出来。

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

我们可以假设对象有一个 timestamp 字段包含最后修改时间。如果我已经在 t1 签出(例如使用ModelForm访问视图),并且对象再次保存在 t2 ,给定 t2 > t1 我不能保存。

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.

推荐答案

覆盖首先检查最后一个时间戳的保存方法:

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

这篇关于如何防止覆盖别人修改的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆