本文介绍了如何为序列化程序分页queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在检索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
这篇关于如何为序列化程序分页queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!