ORM Django LEFT JOIN + GROUP BY

时间:2015-04-14 17:07:01

标签: sql django group-by left-join aggregate-functions

我的Django项目中有以下模型:

class Player(models.Model):
    name = models.CharField()

class Team(models.Model):
    name = models.CharField()

class Membership(models.Model):
    player = models.ForeignKey(Player)
    team = models.ForeignKey(Team)
    date_joined = models.DateField()
    date_leaved = models.DateField(blank=True, null=True)

我想在Django级别创建一个可以执行该操作的视图:

CREATE VIEW last_contract_expire AS
SELECT Player.name, MAX(Membership.date_leaved)
FROM player LEFT OUTER JOIN membership ON membership.player.id=player.id
GROUP BY player.id;

1 个答案:

答案 0 :(得分:0)

Django目前不支持SQL视图(see this ticket)。 Django也不直接支持SQL GROUP BY。无论如何,你可以这样做:

def last_contract_expire():
    return Player.objects.all().annotate(max_date_leaved=Max('membership__date_leaved'))

这将返回所有玩家,每个玩家将拥有namemax_date_leaved属性。希望这有帮助