4

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

diegueus9
  • 29,351
  • 16
  • 62
  • 74
loki
  • 2,271
  • 5
  • 32
  • 46

1 Answers1

9

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
jdi
  • 90,542
  • 19
  • 167
  • 203
  • It works, now i tried self._prev_value = 0 before trying your version and it didn't work, i wonder what get's called first __init__, clean or save – loki Apr 26 '12 at 19:15
  • 2
    @user1108631: `__init__` is called when your instance is being created from a database query or manually creating a new one. Clean is called later by a validation process. – jdi Apr 26 '12 at 19:17