How to break pages into nested relationships?

I read the django-rest-framework nested relationship :

You can see tracksin 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')

The official site does not provide a way of pagination tracksin AlbumSerializer, if the number of tracks is too large, how to implement pagination for tracks?


EDIT

I want to paginate by passing the page number to the API.

+4
source share
1 answer

There are several paginator classes in Django that can help you build it yourself.

If you want to create pagination, you can do it like this:

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(), - .

-1

Source: https://habr.com/ru/post/1689958/


All Articles