使模型的所有对象可用于其他模型

时间:2014-10-28 13:37:56

标签: python django

如果我有以下型号:

class Player(models.Model):
  game = models.ForeignKey('Game', null=True, blank=True)

class Game(models.Model):
  score = models.IntegerField(default=0)

这样,如果我有多个类型为game的对象,p.game(其中p是Player类型的对象)将始终为None。如果我添加了类型为Game的n个对象,我希望它们可供所有玩家使用,但每个玩家都应拥有自己的分数。我怎样才能做到这一点? Django 1.4.2如果重要的话。

2 个答案:

答案 0 :(得分:1)

我认为Django ManyToManyField就是答案:

https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

更新:分数可以是M2M中的额外字段,如下所示:https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

答案 1 :(得分:0)

您可以创建第三个模型并保持简单。

class Player(models.Model):
  name = models.CharField(default="John Rambo", max_length=256)

class Game(models.Model):
  name = models.CharField(default="Pack-man", max_length=256)

class Instance(models.Model):
  player = models.ForeignKey(Player)
  game = models.ForeignKey(Game)
  score = models.IntegerField(default=0)

我认为你是初学者,所以添加一个例子:

In [1]: from xyz.models import *

In [2]: player = Player()
In [3]: player.save()

In [4]: game = Game()
In [5]: game.save()

In [6]: instance1 = Instance.objects.create(player=player, game=game, score=0)

In [7]: player.instance_set.all()
Out[7]: [<Instance: Instance object>]

In [8]: game.instance_set.all()
Out[8]: [<Instance: Instance object>]

In [9]: all_scores_for_john_rambo = [i.score for i in player.instance_set.filter(player__name="John Rambo")]
Out[9]: [0]