Django模型中的必填字段不是必填项?
我有以下Django模型:
I have the following Django model:
class Customer(models.Model):
email = models.EmailField(unique=True)
在我的测试用例中,我没有电子邮件就实例化了它.
In my testcase, I instantiate it without an e-mail.
class CustomerTestCase(TestCase):
def test_that_customer_can_be_created_with_minimum_data(self):
customer = Customer.objects.create()
print(customer.__dict__)
我希望它会引发错误,但是它会创建一个带有空字段 email
的记录.如果我明确地说 null = False
和 blank = False
,也会发生同样的事情.相反,它只会打印空的电子邮件.
I expect it to raise an error, but it creates a record with an empty field email
. The same thing happens if I explicitly say null=False
and blank=False
. Instead, it just prints the empty email.
{'email': ''}
我想念什么?
You're missing the fact that validation is not run on save - see the validation docs:
请注意,保存模型时验证器不会自动运行,但是如果您使用的是ModelForm,它将在表单中包含的任何字段上运行验证器.
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
正如该文档所暗示的那样,通常在表单的上下文中进行验证.
As that doc implies, usually validation is carried out in the context of a form.