gpt4 book ai didi

python - 如何对嵌套关系进行分页?

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:35 25 4
gpt4 key购买 nike

我读了django-rest-framework nested-relationships :

可以在AlbumSerializer中看到轨道:

class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('order', 'title', 'duration')

class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)

class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')

官网没有给出对AlbumSerializer中的轨道进行分页的方法,如果轨道数过多,如何实现轨道分页?


编辑

我想通过将页码传递给 API 来对其进行分页。

最佳答案

Django have some paginator classes that can help you build it on your own.

如果你想构建一个分页,你可以这样做:

from django.core.paginator import Paginator

def viewPage(request, page):
paginator = Paginator(data, 10) # 10 being how many objects per page you want, data being an array of tracks
try:
tracks = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
tracks = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
tracks = paginator.page(paginator.num_pages)
return render(request, 'view_page.html', {
'tracks': tracks,
})

您需要提供给 Paginator() 的数据是作为可迭代对象的整个轨道集合。

关于python - 如何对嵌套关系进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com