IntegerRangeField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        validators = []
        if isinstance(max_value, int):
            validators.append(MaxValueValidator(max_value))
        if isinstance(min_value, int):
            validators.append(MinValueValidator(min_value))
        models.IntegerField.__init__(
            self,
            verbose_name,
            name,
            validators=validators,
            **kwargs
        )

    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)

More like this

  1. OrderField by zenx 4 years, 3 months ago
  2. Fixed-point Decimal model field with integer storage by lanzz 1 month, 1 week ago
  3. TinyIntegerField by Lacour 2 years, 8 months ago
  4. keeping Model and Field History (everywhere) by buriy 5 years, 7 months ago
  5. BigIntegerField and BigAutoField by fnl 5 years, 4 months ago

Comments

(Forgotten your password?)