Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Override min_value and max_value in IntegerField Django
class A:
  min_v = 1
  max_v = 15
  number1 = IntegerField(min_value=min_v, max_value=max_v)

class B(A):
   number2 = IntegerField(min_value=A.min_v, max_value=A.max_v)

class C(B):
  min_v = 2
  max_v = 20

How to make both number1 and number2 to be in range from 2 to 20 in class C?

I'm thinking about two ways:

  1. In __init__ redeclare self.fields['number1'] like IntegerField(min_value=self.min_v)
  2. Set self.fields['number1'].min_value=self.min_v in __init__ and override setattr() to add validator.

What is the best and the cleanest way?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It might be better to add these bounds as validators to the the bounds in the __init__ method of class A and class B. This will make these transparent to C and furthermore C can for example define another IntegerField for that name and thus specify a different widget for that:

from django.core import validators

class A:
    number1 = IntegerField()
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        number1 = self.fields['number1']
        number1.validators.append(validators.MinValueValidator(self.min_v))
        number1.validators.append(validators.MaxValueValidator(self.max_v))
        number1.widget.attrs['min'] = number1.min_value = self.min_v
        number1.widget.attrs['max'] = number1.max_value = self.max_v

class B(A):
    number2 = IntegerField()
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        number2 = self.field['number2']
        number2.validators.append(validators.MinValueValidator(self.min_v))
        number2.validators.append(validators.MaxValueValidator(self.max_v))
        number2.widget.attrs['min'] = number2.min_value = self.min_v
        number1.widget.attrs['max'] = number2.max_value = self.max_v
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda