使用 ForeignKey 访问两个模型的匹配条目

Accessing matching entry of two models using ForeignKey

我有三个模型:游戏模型、分销商模型和关系模型。关系模型有两个外键。一个链接到游戏模型,另一个链接到分销商模型。我需要在模板上(在同一视图上)访问匹配条目的游戏模型和关系模型的数据。

Models.py

class Game(models.Model):
    name = models.CharField(max_length=100, unique=True)
    

class Distributor(models.Model):
    dist = models.CharField(max_length=30, unique=True)


class Relation(models.Model):
    game = models.ForeignKey('Game', on_delete=models.CASCADE)
    distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE)

Views.py

class GameDetailView(DetailView):
    model = models.Game
    context_object_name = 'game_detail'
    template_name = 'gamesDB/game_detail.html'

    def get_context_data(self, **kwargs):
        context = super(GameDetailView, self).get_context_data(**kwargs)
        context.update({
            'game_status': models.Relation.objects.all()
        })
        return context

我觉得我的看法不对。但我找不到让它工作的方法。如何在模板上访问 Relation 模型中添加到 Game 模型上的匹配游戏的数据?提前致谢。

根据文档,使用 DetailView 您可以使用 self.object 获取 Game 实例:

While this view is executing, self.object will contain the object that the view is operating upon.

然后您可以这样过滤:

    def get_context_data(self, **kwargs):
        context = super(GameDetailView, self).get_context_data(**kwargs)
        context.update({
            'game_status': models.Relation.objects.filter(game=self.object)
        })
        return context

或者使用该实例通过遵循关系 backwards:

来获取所有相关的 Relations
    def get_context_data(self, **kwargs):
        context = super(GameDetailView, self).get_context_data(**kwargs)
        context.update({
            'game_status': self.object.relation_set.all()
        })
        return context