简体   繁体   English

如何检查Django模型上的先前值

[英]how to check a previous value on a django model

I've got a django model with a field that i want to be always greater than the previous one of the same model instance after an update, like this: 我有一个django模型,其字段我希望在更新后总是大于同一模型实例的前一个,如下所示:

class MyModel(models.Model):
    version = models.FloatField()
    prev_value = 0

    def clean(self):
        if self.version <= self.prev_value:
             raise ValidationError('error msg')

    def save(self,*args,**kwargs):
        super(MyModel, self).save(*args, **kwargs)
        self.prev_value = self.version

i know that clean is working fine because i've got other validation on the same methon and it's working just fine, what i'm doing wrong and how can i fix it ?. 我知道clean工作正常,因为我在同一个methon上进行了其他验证,并且工作得很好,我做错了什么,我该如何解决? thanks in advance. 提前致谢。

I tested it and it didn't throws any error messages on updates with verion < prev_value 我测试了它,并且在verion <prev_value的更新中未引发任何错误消息

Edit: im using new django 1.4 编辑:即时通讯使用新的Django 1.4

model subclasses actually end up having a metaclass reformat all their class attributes. 实际上,模型子类最终会在其所有类属性中重新设置元类。 So you shouldn't be initializing a plain value as a class attribute. 因此,您不应将纯值初始化为类属性。 You should do it in the __init__ 您应该在__init__执行此操作

class MyModel(models.Model):
    version = models.FloatField()

    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)
        self._prev_value = self.version

    def clean(self):
        if self.version <= self._prev_value:
             raise ValidationError('error msg')

    def save(self,*args,**kwargs):
        super(MyModel, self).save(*args, **kwargs)
        self._prev_value = self.version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM