ORM - Django查询分组并加入自身

时间:2015-06-01 18:23:42

标签: python django join orm django-queryset

我正在开发一个程序跟踪你已经在dota2上玩过的人,但我不知道如何将这个SQL查询翻译成django查询。

模型是:

class Match(models.Model):
    ...

class Account(models.Model):
    ...

class MatchPlayer(models.Model):
    match = models.ForeignKey(Match)
    player_account = models.ForeignKey(Account)
    ...

我要翻译的查询类似于:

SELECT count(*), dmp1.player_account_id, dmp2.player_account_id 
FROM matchplayer dmp1
JOIN  matchplayer dmp2 on dmp1.match_id = dmp2.match_id
WHERE dmp1.player_account_id=<some account id>
GROUP BY 2, 3
ORDER BY 1 desc

是否可以将其转换为django查询,或者我必须将其用作SQL?

1 个答案:

答案 0 :(得分:0)

假设您想知道与pk = 1的玩家玩过的玩家:

queryset = Account.objects.filter(matchplayer__match__in=[m.pk for m in Match.objects.filter(matchplayer__player_account=1)]).exclude(pk=1).annotate(count=Count('matchplayer__match'))

您将获得所有匹配玩家的查询集,每个对象包含一个新属性“count”,对应于特定玩家对目标玩家pk = 1的次数。所以,你可以这样做(假设Account对象有一个'name'字段):

[(p.name, p.count) for p in queryset]