Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!