How to paginate queryset for Serializer

寵の児 提交于 2019-12-12 07:07:48

问题


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

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


回答1:


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

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



来源:https://stackoverflow.com/questions/47884850/how-to-paginate-queryset-for-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!