尝试显示相关GenericForeignKey的嵌套表示时出错

时间:2016-02-18 11:37:42

标签: python django django-rest-framework

我想在Django Rest Framework中显示相关GenericForeignKey的嵌套表示。这就是我的尝试:

class ContentRelatedField(serializers.RelatedField):

    def to_representation(self, value):
        if isinstance(value, Membership):
            return MemberSerializer

        return None


class ListSerializer(serializers.ModelSerializer):

    content_object = ContentRelatedField(read_only=True)
    class Meta:
        model = User
        fields = ('id', 'description', 'content_object')

出现以下错误:

<class 'app.serializers.MemberSerializer'> is not JSON serializable

1 个答案:

答案 0 :(得分:2)

您不仅应该返回类MemberSerializer类,还应该返回它的序列化实例。将此行更改为:

return MemberSerializer(value).data