Django:限制OnetoMany关系中的关系数量
您好,我希望将外键关系限制为特定数字。
假设一支篮球队只能有 12 个人。
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 名球员?
还有任何额外的创建 python 错误吗?
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>
** is there an option to would limit up to 12 players per team here?
with any additional creating a python error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据ForeignKey 定义,没有直接的方法来限制团队中的玩家数量。但是,这可以通过对模型进行一些操作来完成。
一种选择是在 Team 上创建一个方法,例如:
然后您希望始终通过此方法添加玩家。
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.
One option would be to make a method on Team, something like:
Then you would want to always add players through this method.
我认为另一种选择是重写 Player 模型上的保存方法,如下所示:
I think another option would be to override the save method on the Player model like this: