Performance improvement when fetching favorites, down to a single, small http request

This commit is contained in:
Eliot Berriot 2019-01-10 11:58:18 +01:00
commit 3916986fb8
No known key found for this signature in database
GPG key ID: DD6965E2476E5C27
4 changed files with 31 additions and 10 deletions

View file

@ -71,3 +71,19 @@ class TrackFavoriteViewSet(
return Response({}, status=400)
favorite.delete()
return Response([], status=status.HTTP_204_NO_CONTENT)
@list_route(methods=["get"])
def all(self, request, *args, **kwargs):
"""
Return all the favorites of the current user, with only limited data
to have a performant endpoint and avoid lots of queries just to display
favorites status in the UI
"""
if not request.user.is_authenticated:
return Response({"results": [], "count": 0}, status=200)
favorites = list(
request.user.track_favorites.values("id", "track").order_by("id")
)
payload = {"results": favorites, "count": len(favorites)}
return Response(payload, status=200)