由於您需要跟蹤註冊並將球員分配到球隊 我沒有看到任何其他方式
。其實從頭開始。
中間(GamePlayerMembership)實例的存在可以表示玩家是否註冊了該遊戲的 。所以我的意見是這樣的:
from django.db import models
class Player(models.Model):
name = models.CharField()
class Game(models.Model):
starts_when = models.DatetimeField()
players = models.ManyToManyField(Player, through='GamePlayerMembership', related_name='games_played')
def register(self, player):
return GamePlayerMembership.objects.create(game=self, player=player)
def assign(self, player, team):
try:
memb = GamePlayerMembership.objects.get(game=self, player=player)
memb.team = team
memb.save()
except GamePlayerMembership.DoesNotExist:
raise Exception('Player has not registered for the game')
class GamePlayerMembership(models.Model):
TEAMS = (
('home', 'Home'),
('guest', 'Guest')
)
game = models.ForeignKey(Game)
player = models.ForeignKey(Player)
team = models.CharField(max_length=5, choices=TEAMS, null=True, blank=True)
class Meta:
unique_together = ('game', 'player')
好的,爲延遲迴復而道歉 - 我分心了。但是,上面的工作,謝謝。我在這裏和那裏添加了一些比特,比如說一個非註冊方法,但這正是我所需要的。再次感謝。 – bodger
@bodger不用擔心,很高興我幫了忙。 – rantanplan