如何为Serializer分页查询集

时间:2017-12-19 10:25:57

标签: django django-forms django-rest-framework django-serializer django-pagination

我正在审核Category及其outfits列表。我的问题是outfits属于category太多了。{/ p>

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

我们可以对其进行分页,以便用户可以先看到outfits并刷新以查看其余outfits吗?

1 个答案:

答案 0 :(得分:2)

如果你想要简单的条件"先24"和"其余的"。您可以通过获取参数来控制它。

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进行完整呈现