ORM Django LEFT JOIN + GROUP BY

ORM Django LEFT JOIN + GROUP BY

我的 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;

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'))

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