Django REST框架中的Paginate关系?

时间:2013-03-25 14:35:45

标签: django api pagination django-rest-framework django-pagination

我们正在为我们的API使用Django REST Framework,我们需要对返回多个项目的关系字段进行分页。

使用类似于documentation

中的示例进行演示
class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title')

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

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

相册的序列化输出示例:

{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse'
    'tracks': [
        {'order': 1, 'title': 'Public Service Annoucement'},
        {'order': 2, 'title': 'What More Can I Say'},
        {'order': 3, 'title': 'Encore'},
        ...
    ],
}

如果专辑中有数百首曲目,则会出现问题。在这种情况下,有没有办法对“曲目”进行分页?

理想情况下,我知道在这种情况下,“轨道”应该指向一个API URL,它只返回特定相册的轨道 - 这反过来可以很容易地分页。该方法的缺点是获得连续前几个轨道所需的额外请求(以及因此延迟等)。在我们的例子中,重要的是我们能够通过对Album API的单个请求获得至少一些轨道,然后在需要时动态加载其余轨道。

DRF是否为此提供任何特定功能或模式?或者有任何工作吗?

3 个答案:

答案 0 :(得分:9)

自DRF 3.1起,PaginationSerializer不受支持。这是解决方案。

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 5
}

serializers.py

from myapp.models import Album, Track
from rest_framework import pagination, serializers

class AlbumSerializer(serializers.HyperlinkedModelSerializer):
    tracks = serializers.SerializerMethodField('paginated_tracks')

    class Meta:
        model = Album

    def paginated_tracks(self, obj):
        tracks = Track.objects.filter(album=obj)
        paginator = pagination.PageNumberPagination()
        page = paginator.paginate_queryset(tracks, self.context['request'])
        serializer = TrackSerializer(page, many=True, context={'request': self.context['request']})
        return serializer.data

class TrackSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Track

或者您可以将def paginated_tracks替换为

from rest_framework.settings import api_settings

    def get_paginated_tracks(self, obj):
        tracks = Track.objects.filter(album=obj)[:api_settings.PAGE_SIZE]
        serializer = TrackSerializer(tracks, many=True, context={'request': self.context['request']})
        return serializer.data

它甚至比上面的查询少一个。

答案 1 :(得分:8)

如果将来有点腐烂,请从上面的Tom链接复制回答:

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

class PaginatedTrackSerializer(pagination.PaginationSerializer):
    class Meta:
        object_serializer_class = TrackSerializer

class AlbumSerializer(serializers.ModelSerializer):

    tracks = serializers.SerializerMethodField('paginated_tracks')


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


    def paginated_tracks(self, obj):
        paginator = Paginator(obj.tracks.all(), 10)
        tracks = paginator.page(1)

        serializer = PaginatedTrackSerializer(tracks)
        return serializer.data

答案 2 :(得分:1)

Malcolm Box和Deepak Prakash的方法可以帮助序列化关联对象,但正如@eugene之前所说,它只适用于单个Alum。对于相册,我们可以这样做:

serializers.py

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

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

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

apis.py

class getAPIView(generics.ListAPIView):
    serializer_class=TrackSerializer
    filter_backends = (filters.OrderingFilter,)
    def get_queryset(self):
        queryset=Track.objects.all()
        return queryset
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        data=serializer.data
        albums=Album.objects.values_list('album_name').all()
        trackObjs=[]
        albumObjs=[]
        self.categoryKeyList(albums,albumObjs)
        if page is not None:
            for p in page:
                for n,i in enumerate(albums):
                     if re.search(str(p.alum),str(i)):
                        albumObjs[n]['track'].append(p)
        data={}
        data['count']=self.get_paginated_response(self).data['count']
        data['next']=self.get_paginated_response(self).data['next']
        data['previous']=self.get_paginated_response(self).data['previous']
        data['pageNumber'] = self.paginator.page.number
        data['countPage'] = self.paginator.page.paginator._count
        serializer=ClientsCategorySerializer(categoryObjs,many=True)
        data['result']=serializer.data
        return Response({'data':data,'success':'1','detail':u'获得客户列表成功'})
    def categoryKeyList(self,albums,albumObjs):
        for i in albums:
            albumObjs={}
            albumObjs['album_name']=i[0]
            track=[]
            albumObj['track']=track
            albumObjs.append(albumObj)

然后你可能会收到回复:

{
    data[
     {
          'album_name': 'The Grey Album',
          'tracks': [
                   {'order': 1, 'title': 'Public Service Annoucement'},
                   {'order': 2, 'title': 'What More Can I Say'},
                   {'order': 3, 'title': 'Encore'},
                      ...

      },
      {'album_name': 'The John Album',
          'tracks': [
                   {'order': 1, 'title': 'Public Annoucement'},
                   {'order': 2, 'title': 'What sd Can I Say'},
                   {'order': 3, 'title': 'sd'},
                      ...
},
 ......
}