drf——定制字段的两种方式
方式一:在序列化类中书写
想要输出以下字段:
——(书名,价格,出版社信息(id,出版社名,出版社地址))
效果如下图:
需要在序列化类下书写以下代码:
class BookSerializer(serializers.Serializer): name = serializers.CharField() price = serializers.CharField()
出版社详情(publish_detail)代码书写:
使用SerializerMethodField来定制:
publish_detail = serializers.SerializerMethodField()
配合get_字段名接着书写:
返回值=字段名
def get_publish_detail(self, book): # print(obj) # 要序列化的book对象 return {'id': book.publish.pk, 'name': book.publish.name, 'addr':book.publish.addr}
# 同样的,我们可以拿出所有的作者信息—— [{name:,phone:},{}]
author_list = serializers.SerializerMethodField() def get_author_list(self, book): l = [] for author in book.authors.all(): l.append({'id': author.pk, 'name': author.name, 'phone': author.phone, 'age': author.author_detail.age}) return l
方式二:在表模型中书写
代码不变,只是将方法移入表模型中(models)
代码如下:
在序列化类下书写以下代码:
class BookSerializer(serializers.Serializer): name = serializers.CharField() price = serializers.CharField() # 1 序列化类中这样写 # 2 到表模型中写一个方法,方法名必须叫 publish_detail,这个方法返回什么,这个字段的value就是什么 publish_detail = serializers.DictField() author_list = serializers.ListField()
模型类中书写:
@property # 将方法伪装成属性 def publish_detail(self): return {'id': self.publish.pk, 'name': self.publish.name, 'addr': self.publish.addr} @property def author_list(self): l = [] for author in self.authors.all(): l.append({'id': author.pk, 'name': author.name, 'phone': author.phone, 'age': author.author_detail.age}) return l
效果不变
视图层代码准备:
from django.shortcuts import render from rest_framework.views import APIView from .models import Book from .serializer import BookSerialzier from rest_framework.response import Response # Create your views here. class BookView(APIView): def get(self, request): qs = Book.objects.all() ser = BookSerialzier(qs, many=True) return Response({'code': 100, 'msg': '成功', 'results': ser.data})