Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda