Django Rest Framework自定义错误消息

时间:2018-11-23 07:00:07

标签: python django django-rest-framework

我正尝试为SlugRelated字段添加自定义字段错误消息,如下所示:

class Test(serializers.ModelSerializers):
    team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name',
                                        error_messages={"does_not_exist": "Team not found"})

按预期工作。我的查询是如何在错误消息中动态传递团队名称。我尝试了以下操作,但没有成功:

class Test(serializers.ModelSerializers):
    team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name',
                                        error_messages={"does_not_exist": f"Team {team} not found"})

1 个答案:

答案 0 :(得分:1)

does_not_exist的默认错误消息采用slug_namevalue作为关键字参数来格式化错误字符串。

解决方案是将team替换为value

解决方案

class Test(serializers.ModelSerializers):
    team = serializers.SlugRelatedField(
        queryset=Team.objects.all(),
        slug_field='name',
        error_messages={"does_not_exist": "Team {value} not found"}
    )

参考:relations:SlugRelatedField Source Code