问题描述
你好,我希望将ForeignKey关系限制为具体数字。
让我们说篮球队只能有12个人。
Hi i was looking to limit a ForeignKey relationship to as specific number.
Lets say there can only be 12 people on a basketball team.
class Team(models.Model):
teamName = models.CharField(max_length = 20)
teamColors = models.CharField(max_length = 20)
... <and so forth>
class Player(models.Models):
team = models.ForeignKey(Team, **)
name = models.CharField(max_length = 20)
heightInches = models.IntegerField()
... <and so forth>
**是否有一个选项可以限制每个团队12位玩家?
** is there an option to would limit up to 12 players per team here?
与任何额外的创建一个python错误?
with any additional creating a python error?
推荐答案
没有直接方式来限制一个团队中的ForeignKey定义的玩家人数。然而,这可以通过一些使用你的模型来完成。
There isn't a direct way to limit the number of players in a team on the ForeignKey definition. However, this can be done with a little bit of working with your model.
一个选项是在Team上创建一个方法,如:
One option would be to make a method on Team, something like:
def add_player(self, player):
if self.player_set.count() >= 12:
raise Exception("Too many players on this team")
self.player_set.add(player)
然后,您可以随时通过此方法添加玩家。
Then you would want to always add players through this method.
这篇关于Django:限制OnetoMany关系中的关系数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!