提问者:小点点

Django viewset错误:“QuerySet”对象没有属性“title”


我试图为Course模型创建一个视图集(简单地显示所有课程),但是当我试图访问它时,我得到了以下错误。 我刚开始创建视图集和Django,我做错了什么?

Django 2.2

错误

AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `CourseSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'title'.

CourseViewSet

class CourseViewSet(viewsets.ModelViewSet):
    def list(self, request):
        queryset = Course.objects.all()
        serializer = CourseSerializer(queryset)
        return Response(serializer.data)

课程化者

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = (
            'id',
            'title',
            'description',
            'active',
            'individual_result',
            'course_duration',
            'video',
            'manager_id'
        )

模型/课程

class Course(models.Model):
    title = models.CharField(max_length=255, blank=False, null=False)
    description = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True)
    individual_result = models.BooleanField(default=False) 
    course_duration = models.CharField(max_length=255, blank=True, null=True)  
    video = models.CharField(max_length=255, blank=True, null=True)  
    manager_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.title

共1个答案

匿名用户

应该使用many=true序列化,因为queryset是可以包含零个,一个或多个元素的对象集合:

serializer = CourseSerializer(queryset, many=True)

有关更多信息,请参见“处理多个对象”部分[drf-doc]。