1

我开始为我的应用程序使用 django-rest-framework,并且我对序列化程序验证有疑问。在文档中,我找到了这个用于对象验证的示例:

from rest_framework import serializers

class EventSerializer(serializers.Serializer):
    description = serializers.CharField(max_length=100)
    start = serializers.DateTimeField()
    finish = serializers.DateTimeField()

    def validate(self, attrs):
        """
        Check that the start is before the stop.
        """
        if attrs['start'] > attrs['finish']:
            raise serializers.ValidationError("finish must occur after start")
        return attrs

这将返回以下内容:

{"non_field_errors": ["finish must occur after start"]}

我的问题是,如何找出哪些字段导致验证失败?在这种情况下 attrs['start'] 和 attrs['finish']。最后我想要这样的东西:

{"non_field_errors": ["finish must occur after start"], 
 "start": ["finish must occur after start"], 
 "finish": ["finish must occur after start"]}  

这样我就可以标记负责的表单字段。我希望这个问题很清楚。谢谢!

4

1 回答 1

3

创建 时ValidationError,可以传入字典而不是字符串。字典期望key是字段名称,而value是错误字符串。

def validate(self, attrs):
    """
    Check that the start is before the stop.
    """
    if attrs['start'] > attrs['finish']:
        raise serializers.ValidationError({"finish": "finish must occur after start"})
    return attrs

这应该会产生如下输出:

{"start": ["finish must occur after start"], 
 "finish": ["finish must occur after start"]}

这听起来像你在找什么。

于 2014-11-18T18:09:18.823 回答