我们使用Django的REST框架我们的API,我们有必要进行分页返回多个项目关系领域。
为了证明使用类似于在实例文档 :
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 - 这反过来又可以很容易地分页。 不利的一面,以这种方法是额外的要求(并因此延迟等),以获得甚至是第几首曲目需要。 在我们的情况下,重要的是我们能够得到至少有几个曲目的跟单请求相册API,然后动态地在需要时加载轨道的其余部分和。
是否DRF提供这方面的任何特定的功能或模式? 还是有什么变通?
由于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
它甚至需要一个比上面少的查询。
回答汤姆的链接复制上面的未来有点腐烂的情况下:
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
马尔科姆盒和迪帕克·普拉卡什的方法都可以帮助串行器relathionship对象,但正如@eugene之前所说的,它仅适用于单一的明矾。 对于一个相册时,我们可以这样做:
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)
则U可以将得到的回应:
{
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'},
...
},
......
}
我创建鉴于文件API,并得到错误警报" Exception Type: KeyError Exception Value:'request'"
。 ü在哪里设置的request
? 我的API代码:
class getAlbumsList(APIView):
def get(self,request,token,format=None):
page = request.query_params.get('page')
tracks = Albums.objects.filter(designer=2)[:3]
serializer = AlbumSerializer(categorys, many=True)
return serializer.data