Home > Net >  How to filter based on friends of the logged in user?
How to filter based on friends of the logged in user?

Time:10-28

I'm doing a leaderboard which it works when filtering from all users. But here I would like to filter based on the friends of the user.

This is how I get a list of friends :

users = self.request.user.friends

and this is my view :

class FriendsDayLeaderBoard(ListAPIView):
    """
    List friends Leaderboard based on XP token by Day

    Get request
    """
    serializer_class = UserLeaderboardSerializer
    queryset = UserLeaderboardTracking.objects.all()
    permission_classes = [IsAuthenticated]


    def filter_queryset(self,queryset):
        users = self.request.user.friends
        return self.queryset.filter(created_at__date=timezone.now()) \
                            .values('user_id', 'user', 'day_streak') \
                            .annotate(xp_val=Sum('xp_value')) \
                            .order_by('-xp_val')[:20] \

UserLeaderboardTracking keeps track of all the users in the app every time they earn xp

tried to loop from a list of friends but not sure how to proceed in that direction

My model:

class UserLeaderboardTracking(models.Model):

    user = models.ForeignKey(to=User, related_name='user_leaderboard', on_delete=models.CASCADE, null=True)
    xp_value = models.PositiveIntegerField(null=True, blank=True)
    day_streak = models.PositiveIntegerField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

CodePudding user response:

If you want to filter UserLeaderBoardTracking only for friends of current user, if i understood your post, you can do like this:

class FriendsDayLeaderBoard(ListAPIView):
    """
    List friends Leaderboard based on XP token by Day

    Get request
    """
    serializer_class = UserLeaderboardSerializer
    queryset = UserLeaderboardTracking.objects.all()
    permission_classes = [IsAuthenticated]


    def filter_queryset(self,queryset):
        users = self.request.user.friends
        queryset = queryset.filter(created_at__date=timezone.now())
        queryset = queryset.filter(user__in=users)
        queryset = queryset.values('user_id', 'user', 'day_streak')
        queryset = queryset.annotate(xp_val=Sum('xp_value'))
        queryset = queryset.order_by('-xp_val')[:20]

        return queryset
  • Related