序列化(正向查询)
from rest_framework import serializers
from users.models import UserInfo
## 正向查询
class UserInfoSerializer(serializers.Serializer):
# 类名小写.外键字段
goods = serializers.CharField(source='goods.type_name',required=False) # 显示一对多字段名称
class Meta:
model = UserInfo
反向查询
- 反向查询是包含关系,eg:路径-->阶段-->课程,所以在
JieDuanSerializer
导入 model/JieDuan
类
- eg:JieDuan().外键字段 获取课程序列化中的所有字段数据,eg:jieduan = JieDuanSerializer(many=True)
# 路径
class PathSerializer(serializers.ModelSerializer):
class Meta:
model = Path
fields = '__all__'
class JieDuanSerializer(serializers.ModelSerializer):
courses = CourseSerializer(many=True)
class Meta:
model = JieDuan
fields = '__all__'
class PathDeepSerializer(serializers.ModelSerializer):
jieduan = JieDuanSerializer(many=True)
class Meta:
model = Path
fields = '__all__'
一对多序列化(反向查找)
''' 一对多序列化(反向查找)'''
class UserTypeSerializer(serializers.Serializer):
type_name = serializers.CharField()
# 法1一对多关联对象序列化:此字段将被序列化为关联对象的主键
userinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
# 法2一对多关联对象序列化:此字段将被序列化为关联对象的字符串表示方式(即__str__方法的返回值)
# userinfo_set = serializers.StringRelatedField(read_only=True,many=True)
# 法3一对多关联对象序列化:使用关联对象的序列化器
# userinfo_set = UserInfoSerializer(many=True)