Django Rest Framework中prefetch_related的嵌套序列化器

z3yyvxxp  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(111)

我尝试用prefetch_related做一个嵌套的序列化器,但它不起作用,下面是我的代码:
models.py

from django.db import models

class Student(models.Model):
    phone = models.IntegerField(null=True)
    birth_date = models.DateField(null=True)
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="student")

class Course(models.Model):
    title = models.CharField(max_length=100, blank=True, default='')

class CourseEnroll(models.Model):
    course = models.ForeignKey(Course, on_delete=models.PROTECT, related_name='course_enroll')
    student = models.ForeignKey(Student, on_delete=models.PROTECT, related_name='student_enroll')

views.py

from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet

from quiz.models import Course
from quiz.serializers import CourseSerializer

class CourseViewSet(mixins.CreateModelMixin,
                    mixins.ListModelMixin,
                    mixins.RetrieveModelMixin,
                    GenericViewSet):

    def get_queryset(self):
        queryset = Course.objects.prefetch_related("course_enroll").all()
        return queryset
    serializer_class = CourseSerializer

serializers.py

from rest_framework import serializers

from quiz.models import Course, CourseEnroll

class CourseEnrollSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseEnroll
        fields = ['id']

class CourseSerializer(serializers.ModelSerializer):
    student_enrolled = CourseEnrollSerializer(many=True, read_only=True)

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

以下是我的repo:https://github.com/congson95dev/regov-pop-quiz-backend-s-v1
我做错什么了吗?请帮忙,谢谢。

0wi1tuuw

0wi1tuuw1#

prefetch_related不会创建嵌套序列化。相反,它用于缓存相关的模型字段,以便在执行查询集时,它不会进行额外的DB调用。
在这里,您使用student_entrolled指向CourseEnrollSerializer,由于字段名称错误,这将无法工作。它应该是:

class CourseSerializer(serializers.ModelSerializer):
    course_enroll = CourseEnrollSerializer(many=True, read_only=True)

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

相关问题