如何从内置唯一字段验证错误响应的django中删除第三个括号'[]'

How to remove third brackets '[]' from django built in unique field validation erro response

这是我的模型

在这个 CustomerAdd table 中,我用 Django 内置 unique=True 设计了 ​​customer_phone。而对于这些独特的领域,Django 提出 验证错误如下: { “customer_phone”:[ “这个 customer_phone 已经被注册了。” ] } 如何从内置验证错误中删除第三个括号!请帮助我。

class CustomerAdd(models.Model):
    user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE)
    is_customer = models.BooleanField('customer status', default=True)
    is_supplier = models.BooleanField('supplier status', default=False)
    customer_name = models.CharField(max_length=100)
    customer_phone = models.CharField(max_length=15, unique=True, error_messages={'unique': "This customer_phone has "
                                                                                            "already been registered."})
    previous_due = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    date = models.DateField(auto_now_add=True)
    picture = models.ImageField(upload_to='customer_add_pics', default='images.png')

    def __str__(self):
        return self.customer_name

    class Meta:
        verbose_name = "Customer Add"
        verbose_name_plural = "Customer Add"

这里是 API 响应:

{
    "customer_phone": [
        "This customer_phone has already been registered."
    ]
}

Django raised validation error following: { "customer_phone": [ "This customer_phone has already been registered." ] }

发生这种情况的原因是因为同一字段可能有 多个 错误。例如,密码字段可能要求它至少包含八个字符,并且至少包含一位数字。通过使用列表,它因此能够列出一个 或更多 个具有相同字段的问题。从模型来看point-of-view,这是一种更合理的报错方式。

您可以实施 custom exception handling [drf-doc] 以仅使用每个字段的第一项:

# <em>app_name</em>/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 = {
            <strong>k: vs[0]</strong>
            for k, vs in exc.detail.items()
        }
        exc = ValidationError(detail=data)
    
    return exception_handler(exc, context)

然后将异常处理程序设置为:

# settings.py

REST_FRAMEWORK = {
    # …,
    'EXCEPTION_HANDLER': '<em>app_name</em>.utils.<strong>custom_exception_handler</strong>'
}

但我认为这不是一个好主意。一个字段可能有多个问题,从而引发多个验证错误。