您好,登录后才能下订单哦!
from rest_framework import serializers
class AuthorSerializer(serializers.Serializer):
nid = serializers.CharField()
name = serializers.CharField()
age = serializers.CharField()
# class BookSerializer(serializers.Serializer):
# # 可以用source修改别名
# xx = serializers.CharField(source='name')
# price = serializers.CharField()
# sb = serializers.CharField(source='publish.city')
# test = serializers.CharField(source='publish.test')
# publish_id = serializers.CharField()
# # SerializerMethodField,可以指定一个方法
# # publish=serializers.SerializerMethodField()
# # # 方法名:叫get_字段名,要传参数,参数是:当前book对象
# # def get_publish(self,obj):
# # # obj 是当前book对象0
# # dic={'name':obj.publish.name,'email':obj.publish.email}
# # return dic
# authors=serializers.SerializerMethodField()
# # def get_authors(self,book):
# # #拿到这本书的所有作者
# # aus=book.authors.all()
# # # 拼出一个列表,列表中套字典,每个字典是一个作者
# # ll=[]
# # for a in aus:
# # ll.append({'name':a.name,'age':a.age})
# # return ll
# def get_authors(self,book):
# #拿到这本书的所有作者
# aus=book.authors.all()
# # 可以继续用序列化类,来处理
# auth_ser=AuthorSerializer(aus,many=True)
# return auth_ser.data
from ap01.models import Book
# class BookSerializer(serializers.ModelSerializer):
# # 必须写一个内部类,名字叫Meta
# class Meta:
# model = Book
# fields = '__all__'
# # 重写属性
# publish = serializers.CharField(source='publish.name')
# authors = serializers.SerializerMethodField()
# def get_authors(self, book):
# # 拿到这本书的所有作者
# aus = book.authors.all()
# # 可以继续用序列化类,来处理
# auth_ser = AuthorSerializer(aus, many=True)
# return auth_ser.data
class BookSerializer(serializers.ModelSerializer):
# 必须写一个内部类,名字叫Meta
class Meta:
model = Book
# fields = '__all__'
# 指定只取这两个字段
fields = ['nid','name']
# 去掉指定的字段
# exclude=['publish','authors']
# fields,跟exclude不能连用
# 指定深度(官方建议小于10,我给你的建议小于3)
# depth = 2
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。