如何为 Serializer 的查询集分页 [英] How to paginate queryset for Serializer

查看:20
本文介绍了如何为 Serializer 的查询集分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检索 Category 及其 outfits 列表.我的问题是有太多 outfits 属于 category.

I'm retreiving Category and its outfits list. My problem is there are too many outfits belong to a category.

class CategoryListAPIView(generics.RetrieveAPIView):
    serializer_class = CategoryDetailSerializer
    ...

class CategoryDetailSerializer(serializers.ModelSerializer):
    outfits = serializers.SerializerMethodField()
    ...

    class Meta:
        model = Category
        fields = (
            ...
            'outfits',
            ...
        )

    def get_outfits(self, obj):  //This is returning 39 items. 
        // Can we paginate this? 
        if obj.outfits is not None:
            return OutfitListSerializer(obj.outfits, many=True).data
        return None

我们可以分页让用户首先看到 24 个 outfits 并刷新以查看其余的 outfits?

Can we paginate it so that user can first see 24 outfits and refresh to see the rest of outfits?

推荐答案

如果你想要简单的条件第一个 24"和其余的".你可以通过获取参数来控制它.

If you want simple condition "first 24" and "the rest". You could control it by get parameters.

def get_outfits(self, obj):
    show_all = self.request.GET.get('show_all')

    if show_all:
        outfits = obj.outfits.all()
    else:
        outfits = obj.outfits.all()[:24]

    return OutfitListSerializer(outfits, many=True).data

现在您可以使用 GET /categories/ 获取前 24 套服装的类别,使用 GET /categories/?show_all=true 获取完整表示

Now you can use GET /categories/ for categories with first 24 outfits and GET /categories/?show_all=true for full representation

这篇关于如何为 Serializer 的查询集分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆