Home > Software design >  Are "max_length" and "choices" in Model's class definition supposed to prev
Are "max_length" and "choices" in Model's class definition supposed to prev

Time:12-09

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!

CodePudding user response:

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()

CodePudding user response:

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
  • Related