【问题标题】:Django model method, referring to other model via FKDjango模型方法,通过FK引用其他模型
【发布时间】:2013-09-09 21:37:37
【问题描述】:

我的模型是这样的:

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

【问题讨论】:

  • 这有什么好运气吗?我认为你肯定是在正确的轨道上。
  • 我尝试了您的最新更新,但它并没有达到我的目标。最新的代码可以很好地遍历所有玩家(我想要),但是内部循环只是遍历每个游戏状态,我只希望内部循环遍历那个特定的玩家和 game.id .. 我会继续尝试,不过谢谢.顺便说一句,在我获得一定的声誉或其他东西之前,我不能投票
  • 啊,我明白了。查看对我的问题的编辑以进行正确查找。作为仅供参考,接受upvoting不同。您可以随时接受您提出的问题的答案_无论_声誉。
  • 您找到解决方案了吗?

标签: django methods models


【解决方案1】:

无需在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 %}

【讨论】:

  • 在这些示例中,我如何指定游戏(用于 GameStatus)?另外,我把这些放在哪里?在视图中?模板?
  • 你如何想要指定游戏?你想通过什么属性来查找游戏?您可能希望在视图中使用它,因为它是业务逻辑。
  • 有一个PK,所以基本上是通过提供一个game_id ...另外,出于好奇来回答原始问题,是否有可能在一个方法中做?编辑:这本质上是游戏状态的左外连接
  • 你一次要问很多东西。让我们一步一步来。这里有一个问题:如果你已经知道游戏的id,为什么还需要通过parent来访问呢?为什么不直接查呢?
  • 因为在我的模板中我使用的是基于“游戏”模型的基于类的视图,因此在该模板中我可以访问 game_id 并且我正在为游戏中的玩家配置文件执行 {% .team.playerprofile_set.all %} 循环... PS - 我是一个完整的 Django n00b
猜你喜欢
  • 2019-08-27
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 2017-10-20
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
相关资源
最近更新 更多