We are using Django REST Framework for our API and we have a need to paginate relationship fields that return multiple items.
To demonstrate using examples similar to those in the 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')
Example serialized output for an Album:
{
'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'},
...
],
}
This becomes problematic where there are say hundreds of tracks in the Album. Is there a way to paginate the 'tracks' in this case?
Ideally, I know that in cases like this, the 'tracks' should maybe point to an API URL that just returns the Tracks for a particular Album - which in turn can be paginated easily. The down side to that approach being the extra request (and hence delay, etc) required to get even the first few tracks. In our case, its important that we be able to get at least a few of the Tracks with the single request to the Album API and then dynamically load the rest of the tracks as and when required.
Does the DRF offer any specific feature or pattern for this? Or are there any work arounds?
Since DRF 3.1,
PaginationSerializer
is not supported. Here's solution.settings.py
serializers.py
OR you can substitute
def paginated_tracks
forIt even requires one less queries than above.
The methods of Malcolm Box and Deepak Prakash do can help to serializer the relathionship objects, but just as @eugene said before, it only works for a single Alum. For a Albums we can do this:
serializers.py
apis.py
Then u may will get the response:
Answer copied from Tom's link above in case of future bit rot:
I create a api in view files, and get error alert
" Exception Type: KeyError Exception Value:'request'"
. Where did u set therequest
? My api code: