即使未将必需的图表字段设置为显式,也会创建实例

时间:2019-09-04 12:09:04

标签: django

我创建了几个像组织这样的模型。我在测试中注意到的问题可以在模型上使用create方法,即使short_description为空也可以保存新实例。

我确实将Validator设置为没有帮助

class Organization(models.Model):
    # auto creates with signals pre_save
    code = models.CharField(
        primary_key=True,
        max_length=255,
        blank=False,
        null=False,
        help_text='Unique code or id that can be used to identify organization'
    )
    name = models.CharField(
        max_length=255,
        blank=False,
        null=False,
        help_text='Short name of the organization'
    )
    short_description = models.CharField(
        max_length=255,
        blank=False,
        null=False,
        help_text='Brief overview of the organization',
        validators=[MinLengthValidator(1)]
    )

测试

# this will pass
@pytest.mark.django_db
def test_organization_create():
    obj = Organization.objects.create(name='TEST')
    assert obj.code

如果我未指定Organization会抛出错误,那么我创建short_description实例的行为就是错误的。

1 个答案:

答案 0 :(得分:1)

  

我在测试中注意到的问题,即使short_description为空也可以在模型上使用create方法,它将保存一个新实例。

那是正确。出于性能原因,Django的ORM调用将忽略验证器。

您可以使用.full_clean() method [Django-doc]来验证对象:

@pytest.mark.django_db
def test_organization_create():
    obj = Organization(name='TEST')
    obj.full_clean()  # will raise an error
    obj.save()
    assert obj.code

Django ModelForm [Django-doc]将完全清除,因此通过表单输入数据将产生有效的对象(对您添加到表单中的字段有效)。这是您应该使用Django的表单来处理用户对模型对象的输入的众多原因之一。