drf高级之——定制返回字段

发布时间 2023-12-21 14:59:07作者: wellplayed

方案一:在表模型(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": "北京"
    }