模型的 class 定义中的 "max_length" 和 "choices" 是否应该防止将无效值插入数据库?

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

我有这样一个模型:

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)

我认为这将确保我无法将“Humongous”之类的字符串添加到大小字段中。然而,我能够使用 get_or_create 函数来插入。
你能解释一下为什么 max_length 和选项没有限制插入吗?
谢谢!

get_or_create()(如 create())不调用 full_clean(),验证函数会检查选项,max_length 等。所以你需要自己运行:

try:
    box = Box.objects.get(**your_get_values)
except Box.DoesNotExist:
    box = Box(**your_get_values, **any_other_values) 
    box.full_clean()
    box.save()

max_length 和选择验证器由 full_clean 调用,如 documentation. 中所述。您可以手动调用此方法:

from django.core.exceptions import ValidationError
try:
    box = Box.objects.create(size="L")
    box.full_clean()
    box.save()
except ValidationError:
    pass