【问题标题】:How to show UniqueTogetherValidator as field error instead of non-field error?如何将 UniqueTogetherValidator 显示为字段错误而不是非字段错误?
【发布时间】:2022-01-05 22:04:46
【问题描述】:

我有一个这样的序列化器:

class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact
        fields = (
            'account', 'first_name', 'last_name', 'email',
            'phone_number',
        )
        validators = [
            UniqueTogetherValidator(
                queryset=Contact.objects.all(),
                fields=['account', 'phone_number'],
                message='A contact with this phone number is already exists.',
            ),
        ]

API 以non_field_errors 形式返回唯一的验证器错误。我想在特定领域展示它。在这种情况下phone_number

我该怎么做?

【问题讨论】:

  • 对此+1。我试图将验证器添加到该字段,但它无权访问实例。来看看现有的序列化器。

标签: python django django-models django-rest-framework django-views


【解决方案1】:

我能够重载 is_valid 方法来执行此添加检查。这不是最干净的方法,因为如果存在错误,它将不会运行,但它是一种解决方法。如果有人有更好的解决方案,那就太好了。

在此示例中,我希望将两个字段一起作为“项目”字段的唯一字段。我首先运行初始验证,以便我可以访问经过验证的数据。然后,如果需要,我使用验证器检查并添加错误。

class SequenceSerializer(serializers.ModelSerializer):

    def is_valid(self, raise_exception=False):
        """Run normal validations then check the fields are unique to the project."""
        if not super().is_valid(raise_exception=False):
            if raise_exception:
                raise ValidationError(self.errors)
            return False 
        
        for field in ["long_name", "short_name"]:
            # Run unique together validation
            validator = UniqueTogetherValidator(
                queryset=Sequence.objects.all(),
                fields=[field, "project",]
            )
            try:
                validator(self.validated_data, self)
            except ValidationError:
                # if it fails, remove field from validated data and add to errors
                del self.validated_data[field]
                self._errors[field] = [f"{field} must be unique to the project"]

        if self._errors and raise_exception:
            raise ValidationError(self.errors)
        
        return not bool(self._errors)

    class Meta:
        fields = ("uuid", "long_name", "short_name", "project")
        model = Sequence

引用的原始is_valid方法:https://github.com/encode/django-rest-framework/blob/71e6c30034a1dd35a39ca74f86c371713e762c79/rest_framework/serializers.py#L212

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 2014-04-05
    • 2020-03-19
    • 2021-10-25
    • 2017-07-07
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多