tags:

views:

18

answers:

1

Does anyone have any clue why this doesn't work as expected.

If i use the python shell and do

team.game_set

or

team.games

It returns an error

AttributeError: 'Team' object has no attribute 'game'

If i create a Game object and call

game.home_team

it returns the correct team object

Heres my model

class Team(models.Model):
    name = models.CharField(blank=True, max_length=100)

class Game(models.Model):
    home_team = models.ForeignKey(Team, related_name="home_team")

UPDATE

I've updated the mode by removing the related_name and i now get this error

app.game: Accessor for field 'home_team' clashes with related field 'Team.game_set'. Add a related_name argument to the definition for 'home_team'.
+2  A: 

Well, you set the related_name attribute. From the documentation:

ForeignKey.related_name
The name to use for the relation from the related object back to this one. See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available.

So if you want to have access to the objects via. team.game_set you have to remove this parameter:

class Game(models.Model):
    home_team = models.ForeignKey(Team)

or you access the games via the attribute home_team (but I guess you just misinterpreted the meaning of related_name):

team.home_team

If your class is going to have a guest_team attribute or multiple relationships to Team in general, you have to set a related name and might want to have something like this:

class Game(models.Model):
    home_team = models.ForeignKey(Team, related_name="home_games")
    guest_team = models.ForeignKey(Team, related_name="guest_games")

and then you can access the games via team.home_games and team.guest_games.

Felix Kling
See update to my question.
dotty
@dotty: Are these the full definitions of your classes? If you have multiple relationships to the same model you have to use `related_name` as mentioned in the documentation.
Felix Kling
Well i have home_team and away_team, i guess using the home_games and away_games would work well.
dotty
Very well explained answer, thank you very much. Helped me understand related_name a lot more.
dotty