首页 > 解决方案 > 使用 ValidationError 和 Constraint(Django 2.2 中的新功能)时的最佳实践是什么?

问题描述

编辑:我正在使用 PostgreSQL

我有一个具有 4 个电话号码字段的模型,并且我在模型级别运行 ValidationError 使用clean

class Person(models.Model):

    personal_phone_mobile = PhoneNumberField()
    personal_phone_direct = PhoneNumberField()
    company_phone_mobile = PhoneNumberField()
    company_phone_direct = PhoneNumberField()

   def clean(self):
        """Ensure that at least one phone number for personal and company 
           contact phone is provided (either mobile or direct)."""

        error_dict = {}
        if self.personal_id_type == 0 and self.personal_id:
            error_dict['personal_id_type'] = ValidationError(
                "ID type can not be 'None' if you have set a value."
            )
        if self.personal_phone_mobile is None and self.personal_phone_direct is None:
            error_dict['personal_phone_direct'] = ValidationError(
                'Please enter at least one personal phone number'
            )
            error_dict['personal_phone_mobile'] = ValidationError(
                'Please enter at least one personal phone number'
            )
        if self.company_phone_mobile is None and self.company_phone_direct is None:
            error_dict['company_phone_direct'] = ValidationError(
                'Please enter at least one company phone number'
            )
            error_dict['company_phone_mobile'] = ValidationError(
                'Please enter at least one company phone number'
            )
        if error_dict:
            raise ValidationError(error_dict)

这按预期工作正常。

在 Django 2.2 中,引入了模型约束,它在数据库级别创建约束。

最佳做法是:

  1. 将模型替换ValidationErrorConstraint
  2. 仅使用ValidationErrors(我不确定上述逻辑是否可以使用Constraint?)
  3. 保留两个?

如果答案是 1 或 3,我将如何ValidationError在 a 中创建与 my 相同的逻辑Constraint

标签: djangodjango-modelsdjango-constraints

解决方案


推荐阅读