django - 使用 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 中,引入了模型约束,它在数据库级别创建约束。
最佳做法是:
- 将模型替换
ValidationError
为Constraint
- 仅使用
ValidationErrors
(我不确定上述逻辑是否可以使用Constraint
?) - 保留两个?
如果答案是 1 或 3,我将如何ValidationError
在 a 中创建与 my 相同的逻辑Constraint
?
解决方案
推荐阅读
- xml - XSLT - 如何将垂直数据集转换为具有已定义标题的水平数据集
- tableau-api - 聚合在两个级别中的任何一个级别
- javascript - 使用克隆节点如何更改子 onclick 参数的属性?
- android - 如何在活动破坏和娱乐之间保持对线程的引用?
- flutter - 跳出无效图像链接的 For 循环 Flutter
- python - 有没有办法自动识别照片中折线图的位置并将其数字化?
- microservices - 我什么时候想创建多个 Verticle(假设我在无状态微服务中使用非阻塞数据库客户端)?
- scala - 将序列连接到地图时的奇怪行为(Scala 2.13)
- python - 在引用之前已分配变量,但仍收到 UnboundLocalError
- angular - Angular Firestore 有时会重复条目