django - 未指定时,Django 模型如何不强制执行必需的模型字段?
问题描述
我创建了一个模型:
class Example(models.Model):
name = models.CharField(max_length=50)
code = models.CharField(max_length=10)
content = models.TextField()
和相应的测试: from django.test import TestCase
from .models import Example
class ExampleTestCase(TestCase):
def setUp(self):
Example.objects.create(name="fff", content="blah blah blah")
def test_length_of_toa_model(self):
"""example model should have length 1 as we created one in setUp"""
length_of_toa = len(Example.objects.all())
self.assertEqual(length_of_toa, 1)
我记得默认行为是它会抛出错误,因为默认情况下代码是必填字段,而不是设置为 null 或空白,那么为什么在这种情况下一切正常?除了测试之外,我还尝试使用 django shell 创建和保存,效果很好。
解决方案
当您通过管理器( .objects )创建对象时,您直接构造 sql 查询,因此您没有任何字段验证。当您通过 django 表单创建/保存对象时,在创建表单之前通过运行 full_clean 方法检查所有字段,
为了强制执行干净的验证,您可以在保存中添加 full_clean,例如:
class MyModel(models.Model):
....
def save(self, *args, **kwargs):
self.full_clean() # if error(field cant blank ..ect) raise a ValidationError
super().save(*args, kwargs
您还可以通过以下约束方法直接在数据库中添加约束:
class MyModel(models.Model):
username = models.TextField()
class Meta:
constraints = [
models.CheckConstraint(check=Q(username__isnull=true), name='username_cant_be_empty') # the username can be empty
]
# when you save this with username empty, integrityError error raised,
在这里查看更多信息: https ://docs.djangoproject.com/fr/3.0/ref/models/constraints/
推荐阅读
- javascript - 在一个简单的翻牌JS函数中解析turned = !turned的逻辑
- ssl - 将 ssl 证书导入 Apache Tomcat
- r - 使用 Caracas 包的 R 中 SymPy 矩阵的平方根
- r - 如何从每个图中删除我不需要的 x 轴值?
- python - 我无法使用带有 chrome 配置文件的 selenium 打开网站
- python - 如何确定更新或删除帖子的正确用户
- scrapy - Scrapy:无法获取数据
- cobol - OpenCOBOL 找不到我的外部模块来运行程序
- c# - 在 datagridview 中处理数据变得非常缓慢
- php - 未定义变量:用户(查看:/home/swit/public_html/manager/resources/views/users.blade.php)