方案一:在表模型(models)中写,在序列化类中映射
模型层书写:
def publish_detail(self): return {'name': self.publish.name, 'city': self.publish.city}
序列化类(serializer)中书写:
publish_detail = serializers.DictField(read_only=True)
前端打印:
"publish_detail": { "name": "北京出版社", "city": "北京" }
方案二:在序列化类中写SerializerMethodField方法,必须配合一个方法 get_字段名
序列化类中书写:
publish_detail = serializers.SerializerMethodField(read_only=True) def get_publish_detail(self, obj): return {'name': obj.publish.name, 'city': obj.publish.city}
前端打印:
"publish_detail": { "name": "北京出版社", "city": "北京" }
标签:返回,city,name,self,detail,publish,定制,序列化,drf From: https://www.cnblogs.com/wellplayed/p/17919061.html