Model Custom Validator between more than one field

4,298 views
Skip to first unread message

Renne Rocha

unread,
Aug 18, 2010, 8:02:33 AM8/18/10
to django...@googlegroups.com
Hello all,

I have created custom validators to my models fields, but I don't
know if it is possible to create a validator for a field that use the
value of other field in its validator.

What I am trying to do:

I have this model:
class MyModel(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField(validators=[my_validator])

And then I want to create a custom validator:

def my_validator(value):
field2_value = value
field1_value = ??? # Can I get this value???

# Just a example of validation
if field1_value > field2_value:
# do something
else:
raise ValidationError('My error!!!')

Is it possible to do this? Or the only way to validate the
relationship between two fields is with form validation?

Thank you!

  Renne Rocha
  renne...@gmail.com
  http://rennerocha.webfactional.com/

Kenneth Gonsalves

unread,
Aug 18, 2010, 8:11:19 AM8/18/10
to django...@googlegroups.com
On Wed, 2010-08-18 at 09:02 -0300, Renne Rocha wrote:
> Is it possible to do this? Or the only way to validate the
> relationship between two fields is with form validation?
>
>

this may help:
http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo#id1
--
regards
Kenneth Gonsalves

Renne Rocha

unread,
Aug 18, 2010, 8:18:47 AM8/18/10
to django...@googlegroups.com
Thank you! It helped me.

I must define the Model.clean() method.

> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
>

skyjur

unread,
Aug 18, 2010, 9:54:22 AM8/18/10
to Django users
No because validator validates a single value and should be universal
for any use. You should put your logic in model`s validation not
field`s.

Or you could use a dirty hack which I do not recommend however I've
used it by myself:

def field1 = models.IntegerField(validators=[validator1])
def field2 = models.IntegerField(validators=[validator2])

def validator1(value):
validator1.my_last_value = value

def validator2(value):
if not validator1.my_last_value == value:
# do somthing
validator1.my_last_value = None # reset it

# note that arrangement of fields is important !
>   renne.ro...@gmail.com
>  http://rennerocha.webfactional.com/
Reply all
Reply to author
Forward
0 new messages