我有两个模型,
Player
- id: int
- name: string
Ball
- type: string
- player_id: int基本上,这个想法是一个球员可以拥有一定数量的球。在ball.type中,球的类型可以是大的或小的(存储为字符串值
现在,我想根据计算出的声誉对球员进行排序。声誉的计算公式如下
reputation = No of Big balls x 10 + No of Small balls
因此,例如,一个球员拥有一个大球和一个小球的声誉将是11。
有人能给出一个关于如何根据这种声誉对用户进行排序的想法吗?谢谢你的帮助。
发布于 2021-02-22 17:18:24
您可以尝试注释并使用它来订购:
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')发布于 2021-02-22 18:48:38
您可以使用Django Manager类。考虑下面的代码:
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")))在您的玩家模型中,您可以使用with_reputation生成一个查询集,该查询集具有声誉注释,您可以对其进行排序
class Player(models):
objects = PlayerManager()现在,在您的代码中,您可以使用Players.objects.with_reputation()获取一个查询集,并将注释reputation添加到每条记录中。然后,您可以使用它来进行排序
Players.objects.with_reputation().order_by('reputation')或者:
Players.objects.with_reputation().filter(name='Sam').ordere_by('reputation')你可以在这里阅读更多关于经理的信息:https://docs.djangoproject.com/en/3.1/topics/db/managers/
https://stackoverflow.com/questions/66312747
复制相似问题