Django Rest框架中的prefetch_related嵌套序列化器



我试图使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']

这是我的回购:https://github.com/congson95dev/regov-pop-quiz-backend-s-v1

我这里做错了什么吗?请帮忙,谢谢。

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']

相关内容

  • 没有找到相关文章

最新更新