gpt4 book ai didi

django - Django 模型中的必填字段不是强制性的?

转载 作者:行者123 更新时间:2023-12-03 21:27:34 24 4
gpt4 key购买 nike

我有以下 Django 模型:

class Customer(models.Model):
email = models.EmailField(unique=True)

在我的测试用例中,我在没有电子邮件的情况下对其进行了实例化。
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 .相反,它只是打印空电子邮件。
{'email': ''}

我错过了什么?

最佳答案

您错过了保存时不运行验证的事实 - 请参阅 the validation docs :

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.



正如该文档所暗示的那样,通常验证是在表单的上下文中进行的。

关于django - Django 模型中的必填字段不是强制性的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com