Search code examples
djangopaginationdjango-querysetdjango-paginationdjango-rest-viewsets

Django Viewset Pagination throws serialization error


I have something like this:

Paginating Viewset:

class FeedViewSet(ModelViewSet):

    queryset = Feed.objects.all()
    serializer_class = FeedSerializer

    def list(self, request, *args, **kwargs):

        paginator = pagination.LimitOffsetPagination()
        paginator.default_limit = 15
        paginator.limit = paginator.get_limit(request)
        paginator.offset = paginator.get_offset(request)
        feeds = paginator.paginate_queryset(Feed.objects.all(), request)
        return Response(
                data={
                        'feeds': feeds,
                        'limit': paginator.limit,
                        'offset': paginator.offset,
                        'overall_count': paginator.count
                    }
                )

Feeds Model:

class Feed(Base):
    headline = models.CharField(max_length=255)
    link = models.CharField(max_length=255, unique=True)
    summary = models.TextField()
    published_date = models.DateTimeField()
    views = models.IntegerField(default=0)
    shares = models.IntegerField(default=0)
    source = models.ForeignKey(Source, on_delete=models.CASCADE, )
    reader = models.ManyToManyField(User, through='Bookmark')

Feed Serializer:

class FeedSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'id',
            'headline',
            'link',
            'summary',
            'published_date',
            'views',
            'shares',
            'source',
            'created',
            'modified',

        )
        model = models.Feed

I am new to Django. I might be absolutely wrong here.

I have gone through official DRF here : http://www.django-rest-framework.org but couldn't figure out the correct way of implementing pagination.

I get something like this : TypeError: Object of type 'Feed' is not JSON serializable

What am I doing wrong? If this is not the right way to do it, how should it be done. What changes do I need to make?


Solution

  • You shoud pass to Response serialized feeds data. For this you need to use serializer:

    def list(self, request, *args, **kwargs):
        serializer = self.get_serializer_class()
        paginator = pagination.LimitOffsetPagination()
        paginator.default_limit = 15
        paginator.limit = paginator.get_limit(request)
        paginator.offset = paginator.get_offset(request)
        feeds = paginator.paginate_queryset(Feed.objects.all(), request)
        return Response(
                data={
                        'feeds': serializer(feeds, many=True).data,
                        'limit': paginator.limit,
                        'offset': paginator.offset,
                        'overall_count': paginator.count
                    }
                )