Django序列化正反向查询
序列化正反向查询(serializers.Serializer)
models.py
class CourseType(Base):
title = models.CharField('课程类别', max_length=16)
sequence = models.IntegerField('展示顺序', default=10)
class Meta:
db_table = 'tb_course_type'
def __str__(self):
return self.title
class CourseTag(Base):
title = models.CharField('课程标签', max_length=16)
sequence = models.IntegerField('展示顺序', default=10)
class Meta:
db_table = 'tb_course_tag'
def __str__(self):
return self.title
class Course(Base):
STATUS = (
('0', '即将上线'),
('1', '已上线'),
('2', '已下线'),
)
title = models.CharField('课程名', max_length=24)
desc = models.CharField('课程描述', max_length=256)
img = models.ImageField('课程logo', upload_to='course', null=True)
course_type = models.ForeignKey(CourseType, verbose_name='课程类型', on_delete=models.SET_NULL, default=None, null=True)
course_tag = models.ManyToManyField(CourseTag, verbose_name='课程标签')
status = models.CharField('课程状态', choices=STATUS, max_length=8, default='1')
attention = models.IntegerField('关注人数', default=0)
learner = models.IntegerField('学习人数', default=0)
class Meta:
db_table = 'tb_course'
def __str__(self):
return self.title
1. 正向查找
serializer.py
class CourseSerializer(serializers.ModelSerializer):
course_type = serializers.CharField(source='course_type.title')
# 正向查找,显示一对多字段名称
class Meta:
model = Course
fields = '__all__'
class CourseTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CourseType
fields = '__all__'
1.1 未使用正向显示效果
1.2 使用正向显示效果
2. 反向查找
serializer.py
class CourseSerializer(serializers.ModelSerializer):
course_type = serializers.CharField(source='course_type.title')
class Meta:
model = Course
fields = '__all__'
class CourseTypeSerializer(serializers.ModelSerializer):
# 一对多关联对象序列化
# Course().course_set 必须用.后面的xxx作为字段名,也就是小写类名_set
# 一个类型对应多个课程,一对多反向查询type包含的哪些course
course_set = CourseSerializer(many=True)
# 方法1:使用关联对象的序列化器
# course_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
# 方法2:此字段将被序列化为关联对象的主键
# course_set = serializers.StringRelatedField(read_only=True, many=True)
# 方法3:此字段将被序列化为关联对象的字符串表示方式(即__str__方法的返回值)
class Meta:
model = CourseType
fields = '__all__'