Home > Net >  How to find the index of a queryset after the database is sorted in Django
How to find the index of a queryset after the database is sorted in Django

Time:10-30

I am making a leaderboard for my quiz. I made this model:

class LeaderBoard(models.Model):
    name = models.CharField(max_length=200)
    score = models.DecimalField(max_digits=4, decimal_places=2)

This is my code for getting a queryset

leaderboad_place = leaderboard.order_by("score").get(name=request.user.username)
            

After I sort my code, I need the index at which my score stands out.

I want the index, I mean the location of the queryset after the database is sorted, my code is not working. Please someone help.

CodePudding user response:

You can make some trick:

#user is name of field which is refered for User Model

leaderboad_places = list(LeaderBoard.objects.all().order_by('-score').values_list('user', flat=True)) 
leaderboad_places.index(request.user)
  • Related