Django 独树一帜
我正在使用Django开发一个足球联赛管理网站。其中,我有以下几种型号:Django 独树一帜,django,django-models,Django,Django Models,我正在使用Django开发一个足球联赛管理网站。其中,我有以下几种型号: class PlayerRole(Model): player = OneToOneField(Player, primary_key=True) team = ForeignKey(Team, null=True) role = CharField(max_length=20, choices=PLAYER_ROLES) #role can be either "Captain" or "
class PlayerRole(Model):
player = OneToOneField(Player, primary_key=True)
team = ForeignKey(Team, null=True)
role = CharField(max_length=20, choices=PLAYER_ROLES)
#role can be either "Captain" or "Regular" for a certain team
class Meta:
unique_together = ("player", "team")
class Season(Model):
start_date = DateTimeField(null=True, blank=True)
end_date = DateTimeField(null=True, blank=True)
label = CharField(max_length=20)
team = ManyToManyField(Team, null=True, blank=True)
player_role = ManyToManyField(PlayerRole, null=True, blank=True)
这样做的目的是记录一名球员在某个赛季中所扮演的角色。现在我想在赛季和球员角色上加上一个独特的约束,这样在一个赛季中球员只能有一个角色,但在多个赛季中球员可以有多个角色。显然,unique\u-together(“赛季”、“球员角色”)
和unique\u-together(self,“球员角色”)
不起作用(这些都是我脑子里想不出来的)
所以我的问题是-如何实现所描述的约束 OneToOneField在
播放器上强制一个unique,因此unique一起是多余的。要使您的模型工作,您应该将其player
更改为ForeignKey
以下型号可能更适合您的需要:
class Season(Model):
start_date = DateTimeField(null=True, blank=True)
end_date = DateTimeField(null=True, blank=True)
label = CharField(max_length=20)
class PlayerRole(Model):
season = ForeignKey(Season)
player = ForeignKey(Player)
team = ForeignKey(Team)
role = CharField(max_length=20, choices=PLAYER_ROLES)
#role can be either "Captain" or "Regular" for a certain team
class Meta:
unique_together = ("season", "player")
# OR, TO ALLOW PLAYERS MOVING BETWEEN TEAM IN SEASON:
# unique_together = ("season", "player", "team")
OneToOneField
在player
上强制一个unique,因此unique\u一起是多余的。要使您的模型工作,您应该将其player
更改为ForeignKey
以下型号可能更适合您的需要:
class Season(Model):
start_date = DateTimeField(null=True, blank=True)
end_date = DateTimeField(null=True, blank=True)
label = CharField(max_length=20)
class PlayerRole(Model):
season = ForeignKey(Season)
player = ForeignKey(Player)
team = ForeignKey(Team)
role = CharField(max_length=20, choices=PLAYER_ROLES)
#role can be either "Captain" or "Regular" for a certain team
class Meta:
unique_together = ("season", "player")
# OR, TO ALLOW PLAYERS MOVING BETWEEN TEAM IN SEASON:
# unique_together = ("season", "player", "team")
如果您想要对self
进行约束,您需要使用主键作为字段,因为这是使每个季节唯一的(“id”,“player\u role”)
。不过在你的例子中,player\u role
是一个M2M字段,我不确定django在一个独特的M2M中的行为。。。这就是为什么这是一个评论/部分答案的原因。:)德国劳埃德船级社!Django抱怨说:tm.seasure:“独一无二”指的是球员的角色。unique_中不支持多个字段。
我想我必须重新考虑此功能的实现。谢谢你,Yuji。如果你想对self
进行约束,你应该使用主键作为字段,因为这是使每个赛季唯一的('id','player\u role')
。不过在你的例子中,player\u role
是一个M2M字段,我不确定django在一个独特的M2M中的行为。。。这就是为什么这是一个评论/部分答案的原因。:)德国劳埃德船级社!Django抱怨说:tm.seasure:“独一无二”指的是球员的角色。unique_中不支持多个字段。
我想我必须重新考虑此功能的实现。谢谢,Yuji。谢谢,这是我在更换模特时忽略的一个好发现。谢谢,这是我在更换模特时忽略的一个好发现。