序列化组件
一 Serialiaer
1.重命名
class BooksSerializer(serializers.Serializer): # 第一种序列化方式 name = serializers.CharField() xxx = serializers.CharField(source='price')
2.取出出版社名字
- 方式一
- 在模型表中重写__str__方法
序列化组将
class BooksSerializer(serializers.Serializer): publish = serializers.CharField()
模型表
class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name
- 方式二
- 用source,拿出出版社城市
组件
class BooksSerializer(serializers.Serializer): publish = serializers.CharField(source='publish.city')
sourse不仅可以指定字段,还可以指定方法
组件
class BooksSerializer(serializers.Serializer): city = serializers.CharField(source='publish.test')
模型表
class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def test(self): return self.city
3.SerializerMethodField,可以指定一个方法
组将
class BooksSerializer(serializers.Serializer): publish = serializers.SerializerMethodField() def get_publish(self, obj): # obj是当前book对象 dic = {'name': obj.publish.email, 'email': obj.publish.name, 'addr': obj.publish.city} return dic
方法内部可以继续用其他的序列化类
from rest_framework import serializers class AuthorSerializer(serializers.Serializer): nid = serializers.CharField() name = serializers.CharField() age = serializers.CharField() class BooksSerializer(serializers.Serializer): authors = serializers.SerializerMethodField() def get_authors(self, book): author = book.authors.all() # 方法内部还可以继续用其他的序列化类 auther_ser = AuthorSerializer(author,many=True) return auther_ser.data
二 ModelSerialiaer
from app01.models import Book class BooksSerializer(serializers.ModelSerializer): class Meta: # model=指定表 model = Book # fields = '__all__' # 指定只取这两个字段 # fields = ['nid', 'name'] # fields,跟exclude不能连用 # 指定深度,就是跨几个表(官方建议小于10,我给你的建议小于3) exclude = ['publish', 'authors'] depth = 1