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

时间:2017-11-28 12:21:02

标签: python django django-rest-framework

我读了django-rest-framework nested-relationships

您可以在tracks中看到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')

官方网站没有提供一种方法来分隔tracks AlbumSerializer,如果曲目数量过大,如何实现曲目的分页?

修改

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

1 个答案:

答案 0 :(得分:-1)

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()提供的数据是整个轨道集合作为可迭代的。