0

我的模型是这样的:

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 属性(如果存在)?

4

1 回答 1

0

无需在PlayerProfile.

您可以使用内置的关系管理器通过 parent 查找此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 %}
于 2013-09-09T21:45:41.170 回答