2

I'm trying to create a ViewSet for the Course model (to simply display all courses), but I'm getting the following error when trying to access it. I'm new to creating ViewSets and Django in general, what am I doing wrong?

Django 2.2

Error

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)

CourseSerializer

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

models/Course

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 Answer 1

3

You should serialize with many=True, since a queryset is a collection of objects that can contain zero, one, or more elements:

serializer = CourseSerializer(queryset, many=True)

For more information, see the Dealing with multiple objects section [drf-doc].

Sign up to request clarification or add additional context in comments.

2 Comments

Ah okay this works, thank you! Sorry for going off-topic but do you maybe also know how to pass something to the request parameter?
@SJ19: what do you mean with "pass something to the request parameter"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.