Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

Here is a simplified version of my models (Django 1.9, if that matters):

class Player(models.Model):

    name = models.StringField()

class Match(models.Model):

    player_1 = models.ForeignKey(Player, related_name="player_1")

    player_2 = models.ForeignKey(Player, related_name="player_2")

Is there any way to add a player.matches field to the model, which would query all matches where the player is player_1 or player_2? Specifically, I want to do this to take advantage of select_related() to reduce n+1 queries when getting matches for each player

I know I can re-structure the database to support that, but would prefer not to.

1 Answer

0 votes
by (25.1k points)

The easiest way would be through a reverse query merge.

class Player(models.Model):

    name = models.StringField()

    def matches(self):

        return self.player_1.all() | self.player_2.all()

Browse Categories

...