Django引发了以下验证错误:
{ "customer_phone": [ "This customer_phone has already been registered." ] }
发生这种情况的原因是,同一个字段可以
倍数
错误。例如,密码字段可以要求至少包含八个字符,并且至少包含一个数字。通过使用列表,它可以列出一个
或者更多
同一领域的问题。从建模的角度来看,这是一种报告错误的更合理的方法。
你可以实现
custom exception handling
Â
[drf-doc]
要对每个字段仅使用第一项,请执行以下操作:
# app_name/utils.py
from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError
def custom_exception_handler(exc, context):
if isinstance(exc, ValidationError) and isinstance(exc.detail, dict):
data = {
k: vs[0]
for k, vs in exc.detail.items()
}
exc = ValidationError(detail=data)
return exception_handler(exc, context)
然后将异常处理程序设置为:
# settings.py
REST_FRAMEWORK = {
# …,
'EXCEPTION_HANDLER': 'app_name.utils.custom_exception_handler'
}
但我认为这是
不
好主意。一个字段可能会有多个问题,从而引发多个验证错误。