您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。