George B
George B

Reputation: 25

How do I set a range for a positive integer where the upper bound would be an input from another field?

Suppose I have two variables A and B, both are positive integers. A can't be less than 1, B can't be greater than A.

In my models I have something like this:

A = models.PositiveIntegerField(validators=[MinValueValidator(1)])
B = models.PositiveIntegerField(validators=[MaxValueValidator(A)])

This gives me the following error:

TypeError: '<=' not supported between instances of 'PositiveIntegerField' and 'int'

Can someone suggest how to implement this kind of logic?

Upvotes: 1

Views: 123

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477513

You perform validation that spans multiple fields in the .clean() method [Django-doc]:

from django.core.exceptions import ValidationError

class MyModel(models.Model):
    a = models.PositiveIntegerField(validators=[MinValueValidator(1)])
    b = models.PositiveIntegerField()

    def clean(self):
        if self.b > self.a:
            raise ValidationError('a should be greater than or equal to b.')

Since these are not field-specific errors, in case you use a ModelForm, it will render these errors as {{ form.non_field_errors }}. For more information, see the Rendering fields manually section of the documentation.

You can make it specific to a field by passing the ValidationError a dictionary with as key the name of the field:

from django.core.exceptions import ValidationError

class MyModel(models.Model):
    a = models.PositiveIntegerField(validators=[MinValueValidator(1)])
    b = models.PositiveIntegerField()

    def clean(self):
        if self.b > self.a:
            raise ValidationError({'b': 'a should be greater than or equal to b.'})

Upvotes: 1

Related Questions