DRF序列化嵌套数据

有如下模型关系

models.py

class Student(models.Model):
    name = models.CharField('学生名', max_length=20)
    is_del = models.IntegerField(default=0)

    def __str__(self):
        return self.name


class Grade(models.Model):
    name = models.CharField('年级名', max_length=20)
    student = models.ManyToManyField(Student)
    is_del = models.IntegerField(default=0)

    def __str__(self):
        return self.name


class School(models.Model):
    name = models.CharField('学校名', max_length=20)
    grade = models.ManyToManyField(Grade)
    is_del = models.IntegerField(default=0)

    def __str__(self):
        return self.name

序列化School的时候可以需要把GradeStudent带上。

serializer.py

class StudentSerializer(ModelSerializer):
    class Meta:
        model = Student
        fields = ('name', 'is_del')


class GradeSerializer(ModelSerializer):
    student = StudentSerializer(many=True)

    class Meta:
        model = Grade
        fields = ('name', 'is_del', 'student')


class SchoolSerializer(ModelSerializer):
    grade = GradeSerializer(many=True)

    class Meta:
        model = School
        fields = ('name', 'is_del', 'grade')

此时数据库查询

[0.000] SELECT "link_school"."id", "link_school"."name", "link_school"."is_del" FROM "link_school"
[0.000] SELECT "link_grade"."id", "link_grade"."name", "link_grade"."is_del" FROM "link_grade" INNER JOIN "link_school_grade" ON ("link_grade"."id" = "link_school_grade"."grade_id") WHERE "link_school_grade"."school_id" = 1
[0.000] SELECT "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE "link_grade_student"."grade_id" = 1
[0.000] SELECT "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE "link_grade_student"."grade_id" = 2
[0.000] SELECT "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE "link_grade_student"."grade_id" = 3

使用Prefetch_related

view.py

class SchoolListView(ListAPIView):
    serializer_class = SchoolSerializer
    queryset = School.objects.all().prefetch_related('grade', 'grade__student')

此时数据库查询只有三条,数量多时效果会比较明显

[0.001] SELECT "link_school"."id", "link_school"."name", "link_school"."is_del" FROM "link_school"
[0.000] SELECT ("link_school_grade"."school_id") AS "_prefetch_related_val_school_id", "link_grade"."id", "link_grade"."name", "link_grade"."is_del" FROM "link_grade" INNER JOIN "link_school_grade" ON ("link_grade"."id" = "link_school_grade"."grade_id") WHERE "link_school_grade"."school_id" IN (1)
[0.000] SELECT ("link_grade_student"."grade_id") AS "_prefetch_related_val_grade_id", "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE "link_grade_student"."grade_id" IN (1, 2, 3)

prefetch_related 使用一条SQL把所有属于 schoolgrade 和所有属于 gradestudent 查出来,用python做关联。
grade 关联的所有 student 存在如下变量中

cache.png

过滤数据

当需要过滤不需要的数据时,可以自定义DRF中的 ListSerializer,重写它的 to_representation方法, 并在serializer中指定 list_serializer_class

class FilterdListSerializer(ListSerializer):
    def to_representation(self, data):
        data = data.filter(is_del=0)   # 过滤已删除的
        return super().to_representation(data)


class StudentSerializer(ModelSerializer):
    class Meta:
        model = Student
        fields = ('name', 'is_del')
        list_serializer_class = FilterdListSerializer


class GradeSerializer(ModelSerializer):
    student = StudentSerializer(many=True)

    class Meta:
        model = Grade
        fields = ('name', 'is_del', 'student')
        list_serializer_class = FilterdListSerializer


class SchoolSerializer(ModelSerializer):
    grade = GradeSerializer(many=True)

    class Meta:
        model = School
        fields = ('name', 'is_del', 'grade')

DRF在meta中获取list_serializer_class,默认使用 ListSerializer

meta = getattr(cls, 'Meta', None)
list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer)
return list_serializer_class(*args, **list_kwargs)

此时数据库查询

[0.000] SELECT "link_school"."id", "link_school"."name", "link_school"."is_del" FROM "link_school"
[0.001] SELECT ("link_school_grade"."school_id") AS "_prefetch_related_val_school_id", "link_grade"."id", "link_grade"."name", "link_grade"."is_del" FROM "link_grade" INNER JOIN "link_school_grade" ON ("link_grade"."id" = "link_school_grade"."grade_id") WHERE "link_school_grade"."school_id" IN (1)
[0.001] SELECT ("link_grade_student"."grade_id") AS "_prefetch_related_val_grade_id", "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE "link_grade_student"."grade_id" IN (1, 2, 3)
[0.000] SELECT "link_grade"."id", "link_grade"."name", "link_grade"."is_del" FROM "link_grade" INNER JOIN "link_school_grade" ON ("link_grade"."id" = "link_school_grade"."grade_id") WHERE ("link_school_grade"."school_id" = 1 AND "link_grade"."is_del" = 0)
[0.000] SELECT "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE ("link_grade_student"."grade_id" = 2 AND "link_student"."is_del" = 0)
[0.001] SELECT "link_student"."id", "link_student"."name", "link_student"."is_del" FROM "link_student" INNER JOIN "link_grade_student" ON ("link_student"."id" = "link_grade_student"."student_id") WHERE ("link_grade_student"."grade_id" = 3 AND "link_student"."is_del" = 0)

又变多了,多出来的最后三条可以看到,分别查了 school_id=1grade, grade=2和3 时的 student

Django文档上说明了原因:

Remember that, as always with QuerySets, any subsequent chained methods which imply a different database query will ignore previously cached results, and retrieve data using a fresh database query.

prefetch_related后再跟filter时会重新去查数据库,所以在序列化 school_id为1的 grade 时查了一次数据库, 序列化 grade_id 为2 和3的 student 时查了两次数据库

**** 解决方法 ****

使用Prefetch对象指定queryset,此时serializer.py中便不需要自定义ListSerializer

views.py

class SchoolListView(ListAPIView):
    serializer_class = SchoolSerializer
    queryset = School.objects.all().prefetch_related(
        Prefetch('grade', queryset=Grade.objects.filter(is_del=0).prefetch_related(
            Prefetch('student', queryset=Student.objects.filter(is_del=0))
        )),
    )

也可以这么写

    queryset = School.objects.all().prefetch_related(
        Prefetch('grade', queryset=Grade.objects.filter(is_del=0)),
        Prefetch('grade__student', queryset=Student.objects.filter(is_del=0))
    )

过滤后的结果


json.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容