Drf之模型层可插拔式序列化(八)最终版
models.py
在模型层定义时,组建好将要被序列话的字段,在serializer 序列化时就可以实现可插拔式序列化
class Teacher(BaseModel):
"""导师"""
role_choices = (
(0, '讲师'),
(1, '导师'),
(2, '班主任'),
)
name = models.CharField(max_length=32, verbose_name="导师名")
role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="导师身份")
title = models.CharField(max_length=64, verbose_name="职位、职称")
signature = models.CharField(max_length=255, verbose_name="导师签名", help_text="导师签名", blank=True, null=True)
class Course(BaseModel):
"""课程"""
course_type = (
(0, '付费'),
(1, 'VIP专享'),
(2, '学位课程')
)
name = models.CharField(max_length=128, verbose_name="课程名称")
course_img = models.ImageField(upload_to="courses", max_length=255, verbose_name="封面图片", blank=True, null=True)
course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型")
class Meta:
db_table = "luffy_course"
verbose_name = "课程"
verbose_name_plural = "课程"
def __str__(self):
return "%s" % self.name
@property
def teacher_name(self):
return self.teacher.name
@property #使用property方法来封装前端需求的字段
def course_teacher(self):
return {
'name': self.teacher.name,
'role': self.teacher.get_role_display(),
'title': self.teacher.title,
'signature': self.teacher.signature,
}
# 普通序列化方式ModelSerializer,序列化表(无深度)
class CourseDetailModelSerializer(ModelSerializer):
teacher = TeacherModelSerializer()
course_category = CourseCategoryModelSerializer()
class Meta:
model = models.Course
fields = ['name', 'course_teacher', 'teacher_name']
class CourseDetailListAPIView(ListAPIView):
queryset = models.Course.objects.all()
serializer_class = serializers.CourseDetailModelSerializer