简体   繁体   中英

Django order by calculated value

I have 2 models,

Player
- id: int
- name: string

Ball
- type: string
- player_id: int

Basically the idea is that a player can posses certain number of balls. The type of the ball can be BIG or SMALL (stored as string value) in ball.type

Now I would like to sort the players based on a calculated reputation. The formula for reputation is as follows

reputation = No of Big balls x 10 + No of Small balls

So for eg the reputation of a player with one big and one small ball would be 11.

Could someone give an idea on how to order users based on this reputation? Thanks for your help.

You can try annotating and using that to order:

from django.db.models import Count, Q, Value

Player.objects.all().annotate(reputation=Count('ball', filter=Q(ball__type="BIG")) * Value(10) + Count('ball', filter=Q(ball__type="SMALL"))).order_by('reputation')

You could make use of Django Manager class. Consider the code:

class PlayerManager(models.Manager):
    def with_reputation(self):
        # using the formula from "Abdul Aziz Barkat"
        return self.annotate(reputation = Count('ball', filter=Q(ball__type="BIG")) * Value(10) + \
                                          Count('ball', filter=Q(ball__type="SMALL")))

and in your Players model you use the with_reputation to generate a queryset that has the reputation annotation, that you can sort

class Player(models):
     objects = PlayerManager()

now in your code you can use Players.objects.with_reputation() to get a queryset with the annotation reputation added to every record. Then you can use that to do the ordering

Players.objects.with_reputation().order_by('reputation')

or:

Players.objects.with_reputation().filter(name='Sam').ordere_by('reputation')

You can read more about managers here: https://docs.djangoproject.com/en/3.1/topics/db/managers/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM