我们正在为我们的API使用Django REST框架,我们需要分页返回多个项目的关系字段.
演示使用与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,该URL只是返回特定相册的曲目,而后者又可以轻松分页.该方法的不利之处是获得甚至前几个轨迹所需的额外请求(因此也是延迟等).在我们的例子中,它的重要性在于,我们可以通过对Album API的单一请求获得至少一些轨道,然后根据需要动态加载其余轨道.
DRF是否提供任何特定的功能或模式?还是有任何工作?
解决方法
从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','tracks') def paginated_tracks(self,obj): paginator = Paginator(obj.tracks.all(),10) tracks = paginator.page(1) serializer = PaginatedTrackSerializer(tracks) return serializer.data