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

137
Visualizações
Are "max_length" and "choices" in Model's class definition supposed to prevent from inserting invalid values into the database?

I have a situation where I have a model like:

class Box(models.Model):
    
  BOX_CHOICES = [('L','Large'),('M','Medium'),('S','Small')]
    
  size= models.CharField(max_length=1,choices=BOX_CHOICES, blank=True, null=True)

I thought that this would ensure that I couldn't add a string like "Humongous" into the size field. And yet, I was able to accomplish just that using the get_or_create function to insert.
Could you please explain how come the max_length and choices did not restrict that from inserting?
Thank you!

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

0

get_or_create() (like create()) doesn't call full_clean(), the validation function which checks things like choices, max_length, etc. So you'll need to run it yourself:

try:
    box = Box.objects.get(**your_get_values)
except Box.DoesNotExist:
    box = Box(**your_get_values, **any_other_values) 
    box.full_clean()
    box.save()
over 4 years ago · Santiago Trujillo Relatório

0

The max_length and choices validators are called by full_clean, as explained in the documentation. You can call this method manually:

from django.core.exceptions import ValidationError
try:
    box = Box.objects.create(size="L")
    box.full_clean()
    box.save()
except ValidationError:
    pass
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