Home > Net >  Accessing matching entry of two models using ForeignKey
Accessing matching entry of two models using ForeignKey

Time:10-05

I have three models: a Game model, a Distributor model and a Relation model. The Relation model has two ForeignKeys. One linking to Game model and other to Distributor model. I need to access on template (on the same view) the data from the Game model and from the Relation model for the matching entry.

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

I think my view isn't right. But I can't find the way to make it work. How can I access on template the data from the Relation model for the matching game added on the Game model? Thanks in advance.

CodePudding user response:

From the docs, with DetailView you can use self.object to get the Game instance:

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

You can then filter like this:

    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

Or use that instance to get all related Relations by following the relationship backwards:

    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
  • Related