Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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 ?. thanks in advance.

I tested it and it didn't throws any error messages on updates with verion < prev_value

Edit: im using new django 1.4

like image 587
loki Avatar asked Jan 17 '23 20:01

loki


1 Answers

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__

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
like image 119
jdi Avatar answered Jan 25 '23 14:01

jdi