DEPARTMENT_CHOICE = (
('BCT','Department Of Electronics and Computer Engineering'),
('BEL','Deparment Of Electrical Engineering'),
('BCE','Deparment Of Civil Engineering'),
('SHE','Deparment Of Science and Humanities'),
('BME','Deparment Of Mechanical Engineering'),
)
department = models.CharField (max_length =10 ,choices = DEPARTMENT_CHOICE,blank=True,verbose_name="Department")
但是如果我们在部门中添加例如ZZZ,它将被添加到数据库中,但是我想防止这种情况。如何防止添加不在选择元组中的项目?
答案 0 :(得分:0)
这些选择只能限制可以通过Django表单输入的内容。手动实例化对象时,可以插入任何值...
我猜想诀窍是不允许用户手动添加任何实例。
答案 1 :(得分:0)
默认情况下,Django ORM不会 not 调用验证程序来检查值是否有意义。 ModelForm
个叫appropriate cleaning and validation [Django-doc]。
但是,可以在保存之前在模型对象上调用.full_clean()
[Django-doc]。万一对象包含无效数据,这将引发错误。例如:
>>> m = Model(department='ZZZ')
>>> m.full_clean()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/some/lib/python3.6/site-packages/django/db/models/base.py", line 1166, in full_clean
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'department': ["Value 'ZZZ' is not a valid choice."]}
因此,如果模型对象不满足未在数据库级别强制执行的约束,则将引发ValidationError
。
请注意,ORM调用仍会规避:例如Model.objects.create(department='ZZZ')
将忽略验证以及批量更新等。