Django模型方法,通过FK引用其他模型

时间:2013-09-09 21:37:37

标签: django methods models

我的模型是这样的:

class PlayerProfile(models.Model):
    user = models.OneToOneField(User)
    team = models.ForeignKey(Team)
    is_captain = models.BooleanField(default=False)
    def __unicode__(self):
        return self.user.get_username()

class Game(models.Model):
    team = models.ForeignKey(Team)
    game_time = models.DateTimeField()
    location = models.CharField(max_length=100)
    def __unicode__(self):
        return self.team.name + ' ' + unicode(self.game_time)

class GameStatus(models.Model):
    game = models.ForeignKey(Game, default=None, null=True)
    team = models.ForeignKey(Team, default=None, null=True)
    player = models.ForeignKey(PlayerProfile, default=None, null=True)
    game_status = models.CharField(max_length=1)

是否可以在PlayerProfile中编写一个可以访问GameStatus模型的方法,以便我可以获得game_status属性(如果存在)?

1 个答案:

答案 0 :(得分:0)

无需在PlayerProfile上编写方法。

您可以使用内置关系管理器通过父PlayerProfile查看此内容,前提是您知道哪个GameStatus属于您需要访问的PlayerProfile

# look up first player returned from the PlayerProfile model manager
player_profile_1 = PlayerProfile.objects.all()[0]

# look up first game status associated with the first player profile, 
# then access the game_status attribute
game_status_1 = player_profile_1.gamestatus_set.all()[0].game_status

<强>更新

如果你可以在这样的循环中访问游戏的game_status

{% for playerprofile in game.team.playerprofile_set.all %}
    {% for game_status in playerprofile.gamestatus_set.get(game_id=game.id) %}
        {{ game_status.game_status }}
    {% endfor %}
{% endfor %}