Sagar
Sagar

Reputation: 21

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 e.g. 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.

Upvotes: 2

Views: 84

Answers (2)

Ouss
Ouss

Reputation: 3855

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/

Upvotes: 1

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

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')

Upvotes: 3

Related Questions