这个案例在这篇文章中得到了完美的描述文档 http://www.django-rest-framework.org/api-guide/relations/#generic-relationships.
所以如果你想序列化AddressType
你需要实现这样的事情:
class ContentObjectRelatedField(serializers.RelatedField):
"""
A custom field to use for the `content_object` generic relationship.
"""
def to_representation(self, value):
"""
Serialize tagged objects to a simple textual representation.
"""
if isinstance(value, Bookmark):
return 'Bookmark: ' + value.url
elif isinstance(value, Note):
return 'Note: ' + value.text
raise Exception('Unexpected type of tagged object')
Where Bookmark
and Note
是可能具有关联内容的对象。
如果你想序列化AddressBook
你可以尝试做这样的事情:
class AddressBookSerializer(serializers.ModelSerializer):
address_object_type = ContentObjectRelatedField()
class Meta:
model = AddressBook
fields = ('id','uuid','address_tag','address_object_type','address1','address2')