Leader Implementation Using Django

I have a model for each user on my site (UserProfile), each profile contains a field called points.

I would like to get -5 +5 users from the current user when sorting by points. How can i do this?

+5
source share
2 answers

You can make two requests: one for users in front of current users and one for users immediately after:

id = current_user.pk
points = current_user.profile.points

before = User.objects.filter(
    Q(profile__points__gt=points) | 
    Q(profile__points=points, pk__lt=id)
).order_by('-profile__points')[:5]

after = User.objects.filter(
    Q(profile__points__lt=points) | 
    Q(profile__points=points, pk__gt=id)
).order_by('profile__points')[:5]

These are the basics for two queries:

  • All users with an account larger than the current user, or with the same account, but with a lower one pk.
  • All users with an account lower than the current user or with the same account, but with a larger one pk.

. , pk . , ( ), :

before = User.objects.filter(
    profile__points__gt=points,
).order_by('-profile__points')[:5]

after = User.objects.filter(
    profile__points__lte=points,
).exclude(pk=id).order_by('profile__points')[:5]

, , , :

id = current_user.pk
points = current_user.profile.points
index = User.objects.filter(
    Q(profile__points__gt=points) |
    Q(profile__points=points, pk__lt=id)
).count()

, , :

User.objects.all().order_by('-profile__points', 'pk')[index - 5:index + 6]

, , , .

+3

, , , - ...

from django.db.models import Sum, Avg

UserProfile.objects.annotate(sum_rating=Sum('sum__points')).order_by('-sum_points')

, .

: , -

UserProfile.objects.filter(whatever here).order_by('-points')[:5]

.order_by('points')[:5]
+1

All Articles