如何为 Serializer 的查询集分页
How to paginate queryset for Serializer
我正在检索 Category
及其 outfits
列表。我的问题是有太多 outfits
属于 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
?
如果你想要简单的条件 "first 24" 和 "the rest"。您可以通过获取参数来控制它。
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
获取完整展示
我正在检索 Category
及其 outfits
列表。我的问题是有太多 outfits
属于 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
?
如果你想要简单的条件 "first 24" 和 "the rest"。您可以通过获取参数来控制它。
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
获取完整展示