from rest_framework import serializers
目前創(chuàng)新互聯(lián)已為千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬空間、網(wǎng)站運(yùn)營(yíng)、企業(yè)網(wǎng)站設(shè)計(jì)、宣城網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
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,可以指定一個(gè)方法
# # publish=serializers.SerializerMethodField()
# # # 方法名:叫g(shù)et_字段名,要傳參數(shù),參數(shù)是:當(dāng)前book對(duì)象
# # def get_publish(self,obj):
# # # obj 是當(dāng)前book對(duì)象0
# # dic={'name':obj.publish.name,'email':obj.publish.email}
# # return dic
# authors=serializers.SerializerMethodField()
# # def get_authors(self,book):
# # #拿到這本書的所有作者
# # aus=book.authors.all()
# # # 拼出一個(gè)列表,列表中套字典,每個(gè)字典是一個(gè)作者
# # ll=[]
# # for a in aus:
# # ll.append({'name':a.name,'age':a.age})
# # return ll
# def get_authors(self,book):
# #拿到這本書的所有作者
# aus=book.authors.all()
# # 可以繼續(xù)用序列化類,來處理
# auth_ser=AuthorSerializer(aus,many=True)
# return auth_ser.data
from ap01.models import Book
# class BookSerializer(serializers.ModelSerializer):
# # 必須寫一個(gè)內(nèi)部類,名字叫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()
# # 可以繼續(xù)用序列化類,來處理
# auth_ser = AuthorSerializer(aus, many=True)
# return auth_ser.data
class BookSerializer(serializers.ModelSerializer):
# 必須寫一個(gè)內(nèi)部類,名字叫Meta
class Meta:
model = Book
# fields = '__all__'
# 指定只取這兩個(gè)字段
fields = ['nid','name']
# 去掉指定的字段
# exclude=['publish','authors']
# fields,跟exclude不能連用
# 指定深度(官方建議小于10,我給你的建議小于3)
# depth = 2