【发布时间】:2021-05-06 19:42:35
【问题描述】:
我正在努力使用注释,但没有找到帮助我理解的示例。以下是我的模型的相关部分:
class Team(models.Model):
team_name = models.CharField(max_length=50)
class Match(models.Model):
match_time = models.DateTimeField()
team1 = models.ForeignKey(
Team, on_delete=models.CASCADE, related_name='match_team1')
team2 = models.ForeignKey(
Team, on_delete=models.CASCADE, related_name='match_team2')
team1_points = models.IntegerField(null=True)
team2_points = models.IntegerField(null=True)
我想最终得到的是 Teams 对象上的注释,它可以为我提供每个团队的总分。有时,一个团队是match.team1(所以他们的积分在match.team1_points),有时他们是match.team2,他们的积分存储在match.team2_points。
这是我得到的最接近的结果,大概尝试了一百次左右:
teams = Team.objects.annotate(total_points =
Value(
(Match.objects.filter(team1=21).aggregate(total=Sum(F('team1_points'))))['total'] or 0 +
(Match.objects.filter(team2=21).aggregate(total=Sum(F('team2_points'))))['total'] or 0,
output_field=IntegerField())
)
这很好用,但(当然)为 pk=21 的团队注释 total_points 到查询集中的每个团队。如果有更好的方法来解决这一切,我很乐意看到它,但除此之外,如果你能告诉我如何将那些“21”值转化为对外部团队 pk 的参考,我认为这会奏效吗?
编辑:我最终结合使用 elyas 的答案和注释原始 SQL 语句来解决我的问题。我无法阻止普通注释从查询集中删除非唯一分数,但原始 SQL 似乎可以工作。
这是原始注释:
teams = Team.objects.raw('select id, sum(points) as total_points from (select team1_id as id, team1_points as points from leagueman_match union all select team2_id as id, team2_points as points from leagueman_match) group by id order by total_points desc;')
【问题讨论】:
标签: django django-queryset django-orm