有没有办法在Serializer中约束一起的值?

时间:2017-12-06 10:00:00

标签: python django django-rest-framework

我有EmailCreateSerializer,我可以让创作者通过receive_group ID或receive_user ID向他们发送电子邮件:

class EmailCreateSerializer(Serializer):
    receive_group = serializers.IntegerField(allow_null=True)
    receive_user = serializers.IntegerField(allow_null=True)

传递receive_group(发送到组)或receive_user(发送给单个用户)。

但是我希望有一个约束,它们(receive_groupreceive_user)都不能为空。
有没有办法在Serializer类中执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以覆盖序列化程序的validate()方法来检查:

class EmailCreateSerializer(Serializer):
    receive_group = serializers.IntegerField(allow_null=True)
    receive_user = serializers.IntegerField(allow_null=True)

    def validate(self, data):
        if data['receive_group'] is None and data['receive_user'] is None:
            raise serializers.ValidationError("Group or User cannot be empty, pass information for at least one of those.")
        return data

文档:http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation