DRF的模型序列化高级运用---外键(一对多ForeignKey,多对多ManyToManyField)
说明
- 本教程适用于有DRF基础知识(序列化)
- 主要内容有
- StringRelateField
- PrimaryKeyRelateField
- SlugRelateField
- deth
- SerializerMethodField
- source
- to_representation
特别强调
在序列化的时候,如果有多个值时,一定要用many=True
instance是序列化数据
data是反序列化数据
在创建模型类时,可以用反向查询(related_name=“要反向查询的字段名”)
StringRelateField
功能:返回模型的显示def str(self): return self.字段
用法:
字段 = serializers.StringRelateField()
PrimaryKeyRelateField
功能:返回关键字段的id、默认返回的就是id(一般不用)
用法:
字段 = serializers.PrimaryKeyRelateField(ready_only=True)
SlugRelateField
功能:返回指定对应关系model中的字段
用法:
字段 = serializers.PrimaryKeyRelateField(
read_only=True,
slug_field='字段名'
)
deth
功能:这个方法可以深度遍历,最高遍历9层
用法:
class Meta:
...
depth=num
SerializerMethodField
功能:自定义显示方法
用法:
字段名(自定义)=serializer.SerializerMethodField()
class Meta:
fields = (....,自定义的字段名)
def get_自定义的字段名(self,obj):
return obj.字段名.方法() #如count()
注:要在Meta的fields中添加自定义字段
source
功能:指定指定对应关系model的字段.
注:单个值时可以直接取字段
多个值时要循环。(for …in …:)
用法:
#单个值:
字段 = serializer.类型(source=字段.关连字段)
#多个值:
字段=自定义类名.(source="反向字段.all"#all是取所有值
自定义序列化的类
class 自定义类名(serializers.类型):
def to_representation(self,value):
data_list = []
for row in value:
data_list.append({'id':row.id,......})
return data_list
to_representation
功能:自定义关连键反回值(在序列化类的后面写)
用法:
def to_representation(self,instance):
representation = super(序列化类,self).to_representation(instance)
representation['字段'] = 序列化类(instance.字段).data
representation['字段'] = 序列化类(instance.字段,many=True).data
return representation