首页 > 解决方案 > 未指定时,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 创建和保存,效果很好。

标签: djangodjango-modelsdjango-orm

解决方案


当您通过管理器( .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/


推荐阅读