Python 复杂Django模型查询
我有以下型号:Python 复杂Django模型查询,python,django,models,Python,Django,Models,我有以下型号: class Vote(models.Model): voter = models.ForeignKey(User) target = model.ForeignKey(User) timestamp = models.DateTimeField() game = models.ForeignKey(Game) step = model.IntegerField() type = models.ForeignKey(VoteType)
class Vote(models.Model):
voter = models.ForeignKey(User)
target = model.ForeignKey(User)
timestamp = models.DateTimeField()
game = models.ForeignKey(Game)
step = model.IntegerField()
type = models.ForeignKey(VoteType)
我需要选择得票最多的目标,如果票数相等,则选择得票最早的目标。可以使用Django ORM吗
更新:事实上,我还有三个字段在投票中:
游戏
,回合
和类型
(我将它们添加到上面的代码中),我需要根据前面给定的约束来选择获胜者,给定一个特定的游戏
,回合
和类型
(例如过滤器)(game=1,step=2,type=3)
)您可以使用注释选择每个用户的投票计数和最早投票时间,然后按注释字段排序并选择第一个:
from django.db.models import Count, Min
winner = User.objects.annotate(vote_count=Count('vote_set'))\
.annotate(first_vote_time=Min('vote_set__timestamp'))\
.order_by('-vote_count', 'first_vote_time')[0]
更新:
您可以应用以下筛选器仅计算特定游戏的投票数:
.filter(vote_set__game=game, vote_set__step=step, vote_set__type=type)
双下划线允许您过滤相关对象的属性
请确保在注释之前应用筛选器,以便只计算正确的投票,并确保投票的所有筛选条件都在同一个筛选器调用中。后面将解释为什么必须执行后者。请参阅django models,Making Questions,遗憾的是,我看不到如何将此解决方案扩展到我的实际问题(请参阅我问题中的更新部分)。