Django查询:从不直接相关的模型中获取值

时间:2017-05-03 23:24:55

标签: python django django-models django-queryset

我希望从Django中不直接相关的模型中获取价值。 我有以下模型:

class Platform(models.Model):
    platform = models.CharField()


class Game(models.Model):
    game = models.CharField()
    genre = models.CharField()


class Link(models.Model):
    game = models.ForeignKey(Game)
    platform = models.ForeignKey(Platform)

我怎样才能获得游戏对象的QuerySet,其中游戏标题(Game.game字段)将被替换为以下模式:游戏(平台)(例如'战地(PS3)')没有额外的命中到数据库?

在SQL中它看起来像这样:

SELECT
  g.id,
  g.game || ' (' || p.platform || ')' AS game
FROM game g INNER JOIN link l ON g.id = l.game_id
  LEFT JOIN platform p ON l.platform_id = p.id;

1 个答案:

答案 0 :(得分:0)

您可以使用link_set来获取游戏的反向查找django documentation

class Platform(models.Model):
    platform = models.CharField()


class Game(models.Model):
    game = models.CharField()
    genre = models.CharField()

    def save(self, *args, **kwargs):
        self.title = "{0} ({1})".format(self.title, self.link__platform)
        super(Game, self).save(*args, **kwargs)


class Link(models.Model):
    class Meta:
        unique_together = ('game', 'platform')
    game = models.ForeignKey(Game)
    platform = models.ForeignKey(Platform)