开发者

Django model help

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

UPDAT开发者_如何学编程E

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'.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜