Home > Blockchain >  how to get object position in a queryset without for loop?
how to get object position in a queryset without for loop?

Time:06-07

i have a queryset with length = 10000 users

sorted_users = User.ojbects.all().order_by("-money")

and i need to get a position of a particular user in this sorted query set,

i can do it with foor loop:

user_position = 1
for account in sorted_users:
    if account.username == "admin":
        break
    my_position  = 1
print(user_position)

it works fine, but in case of growing user numbers for example to 100 000, it would take a long time to count users position every time, for loop is slow

how can i make it faster, without a for loop?

CodePudding user response:

You can try getting list of user ids and then check index of your admin user:

users_ids = list(User.objects.all().order_by("-money").values_list('id', flat=True))
admin_index = users_ids.index(<admin_id>)
print(admin_index)
  • Related