Django Viewset Pagination引发序列化错误

时间:2018-03-23 10:12:51

标签: django pagination django-queryset django-pagination django-rest-viewsets

我有这样的事情:

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
                    }
                )

Feed Feed:

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

我是Django的新手。我可能在这里绝对错了。

我在这里通过官方DRF:http://www.django-rest-framework.org但是无法找出实施分页的正确方法。

我得到这样的话:TypeError: Object of type 'Feed' is not JSON serializable

我做错了什么?如果这不是正确的方法,应该怎么做。 我需要做出哪些改变?

1 个答案:

答案 0 :(得分:1)

您应该传递给Response序列化供稿数据。为此,您需要使用序列化器:

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
                }
            )