我想在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
答案 0 :(得分:2)
您不仅应该返回类MemberSerializer类,还应该返回它的序列化实例。将此行更改为:
return MemberSerializer(value).data