import itertools

from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models


class IntegerField(models.IntegerField):
    def __init__(self, *args, min_value=None, max_value=None, validators=tuple(), **kwargs):
        self.min_value, self.max_value = min_value, max_value
        if min_value is not None:
            validators = itertools.chain((MinValueValidator(min_value),), validators)
        if max_value is not None:
            validators = itertools.chain((MaxValueValidator(max_value),), validators)
        super().__init__(*args, validators=validators, **kwargs)

    def formfield(self, **kwargs):
        if self.min_value is not None:
            kwargs['min_value'] = self.min_value
        if self.max_value is not None:
            kwargs['max_value'] = self.max_value
        return super().formfield(**kwargs)
