restframework 序列化补充(自定义ModelSerializerl)

一、知识点

1、source

title = serializers.CharField(source='courses.title')

source用于one2one、foreginkey、choices,用与获取一个结果

2、SerializerMethodField

    title = serializers.CharField(source='courses.title')
    recommend_courses = serializers.SerializerMethodField()
    chapter = serializers.SerializerMethodField()

    def get_recommend_courses(self, obj):
        rc_list = obj.recommend_courses.all()
        return [{'id': rc_obj.id, 'title': rc_obj.title} for rc_obj in rc_list]

    def get_chapter(self, obj):
        query_set = obj.courses.chapter_set.all()
        print("=============>", query_set)  # <QuerySet [<Chapter: 基础语法>, <Chapter: 函数>, <Chapter: 面向对象>]>
        return [{'id': obj.id, 'name': obj.name} for obj in query_set]

    class Meta:
        model = CourseDetail
        fields = ['id', 'slogan', 'why', 'title', 'recommend_courses', 'chapter']

SerializerMethodField用于many2many 和 获取的结果是多个值(queryset) 外键的反向查询

3、depth(一般不用)

depth 按照表的关系

当数据量较大时,给前端开发人员取数据造成了不便

depth值 0-10

class CourseDetailSerializer(serializers.ModelSerializer):
    """
    课程细节序列化
    """
    class Meta:
        model = CourseDetail
        # fields = ['id', 'slogan', 'why', 'title', 'recommend_courses', 'chapter']

        fields = '__all__'
        depth = 0

a、depth为0

 

 b、depth为1

 

二、例子:

models.py

from django.db import models

# Create your models here.


class Course(models.Model):
    """
    课程表
    """
    title = models.CharField(verbose_name="课程名称", max_length=32)
    course_img = models.CharField(verbose_name="课程图片", max_length=128)
    level_choices = (
        (1, '初级'),
        (2, '中级'),
        (3, '高级')
    )
    level = models.IntegerField(verbose_name="课程等级", choices=level_choices)

    def __str__(self):
        return self.title


class CourseDetail(models.Model):
    """
    课程细节表
    """
    courses = models.OneToOneField(verbose_name="课程表", to="Course", on_delete=models.CASCADE)
    slogan = models.CharField(verbose_name="标语", max_length=255)
    why = models.CharField(verbose_name="为什么要学?", max_length=255)
    recommend_courses = models.ManyToManyField(verbose_name="推荐课程", to="Course", related_name="rc")

    def __str__(self):
        return self.courses.title


class Chapter(models.Model):
    """
    课程章节表
    """
    num = models.IntegerField(verbose_name="章节")
    name = models.CharField(verbose_name="章节名称", max_length=32)
    courses = models.ForeignKey(verbose_name="所属课程", to="Course", on_delete=models.CASCADE)

    def __str__(self):
        return self.name

序列化

from api.models import Chapter, Course, CourseDetail
from rest_framework import serializers

#


class CourseSerializer(serializers.ModelSerializer):
    """
    课程表序列化
    """
    level = serializers.CharField(source="get_level_display")

    class Meta:
        model = Course
        fields = ['id', 'title', 'course_img', 'level']


class CourseDetailSerializer(serializers.ModelSerializer):
    """
    课程细节序列化
    """
    title = serializers.CharField(source='courses.title')
    recommend_courses = serializers.SerializerMethodField()
    chapter = serializers.SerializerMethodField()

    def get_recommend_courses(self, obj):
        rc_list = obj.recommend_courses.all()
        return [{'id': rc_obj.id, 'title': rc_obj.title} for rc_obj in rc_list]

    def get_chapter(self, obj):
        query_set = obj.courses.chapter_set.all()
        print("=============>", query_set)  # <QuerySet [<Chapter: 基础语法>, <Chapter: 函数>, <Chapter: 面向对象>]>
        return [{'id': obj.id, 'name': obj.name} for obj in query_set]

    class Meta:
        model = CourseDetail
        fields = ['id', 'slogan', 'why', 'title', 'recommend_courses', 'chapter']


class ChapterSerializer(serializers.ModelSerializer):
    """
    课程章节序列化
    """
    class Meta:
        model = Chapter
        fields = '__all__'

 

posted @ 2019-09-16 23:22  市丸银  阅读(556)  评论(0编辑  收藏  举报