Atma
Atma

Reputation: 29775

how to get opposite side of a foreign key relation in django

I have the following relationships:

class Team(models.Model):
    name = models.CharField(max_length=255)

    def players(self):
         ????

class Player(models.Model):
    user = models.OneToOneField(User, related_name="player")
    team = models.ForeignKey(Team)

From the team object, I would like to get all the players that belong to it.

How can I get the values in this opposite relationship?

Upvotes: 1

Views: 1862

Answers (2)

Geo Jacob
Geo Jacob

Reputation: 6009

You can do like this;

def players(self):
     return self.player.all()

Upvotes: 0

solarissmoke
solarissmoke

Reputation: 31464

This is covered in some detail in the documentation on following relationships backward.

Given a Team object team, you get the players with:

team.player_set.all()

You can override the player_set name by setting the related_name parameter in the ForeignKey definition.

Upvotes: 4

Related Questions