Ben Muschol
Ben Muschol

Reputation: 607

Django: ManyToMany field with multiple fk fields

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.

Upvotes: 1

Views: 45

Answers (1)

Hybrid
Hybrid

Reputation: 7049

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

Upvotes: 2

Related Questions