与 django 的一对多关系
我打算创建一个团队系统,每个团队可以包含多个参赛者。参赛者实际上是auth.User
。类似于:
Team:
Contestant1
Contestant2
.
.
ContestantN
由于参赛者实际上是一个用户,我无法修改它以拥有团队的外键。实现这一目标的最佳方法是什么?
我的想法是:
- 为指向团队的用户创建一个
OneToOne
配置文件。 - 定义用户和团队之间的
ManyToMany
关系,其中用户必须是唯一的。
暂停
我正在重新设计我的应用程序的结构,所以我将再次重新表述这个问题
感谢您的回复,我会考虑一下,看看其中是否合适。
I intend to create a teaming system, where each team may contain multiple contestants. The contestants is actually auth.User
. Something similar to:
Team:
Contestant1
Contestant2
.
.
ContestantN
Since a contestant is actually a user which I cannot modify to have a foreignkey to team. What is the best way to achieve this?
The ways I though was:
- Create a
OneToOne
profile for user which points to a team. - Define a
ManyToMany
relationship between user and team where user has to be unique.
A Pause
I am redesigning the structure of my application, so I will rephrase the question again
Thanks for your replies, I will consider them and see if one of them fits.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样做:
这允许一个用户参加不同的团队,但如果您不想允许这样做,您可以将 unique=True 添加到 Contestant.user >。
You can do this:
This allows one user to take part in different teams, but if you don't want to allow this, you can add unique=True to Contestant.user.
最好的方法是扩展默认帐户的功能并创建新的用户模型。然后,新的用户模型可以具有团队的外键。像这样。
现在您可以使用“UserExtended”代替普通用户。
The best way would be to extend the functionality of default accounts and create a new user model. The new user model can then have a foreign key to team. Like this.
Now you can use the "UserExtended" in place of normal User.
我将在
Team
模型上创建一个contestants
字段,如下所示:您无法在 ManyToManyField 上指定
unique=True
。好消息是,它不会将同一参赛者两次添加到同一团队,因此您无需检查参赛者是否是唯一的。I would create a
contestants
field on theTeam
model like so:You can't specify
unique=True
on a ManyToManyField. The good news is that it won't add the same contestant to the same team twice so you won't need to check if the contestant is unique.我想说你最好的选择是创建一个
参赛者
模型。您最终可能需要存储有关特定于球队但与球员分开的参赛者的更多信息(例如参赛者是否是首发、参赛者的号码等)。创建Contestant
模型允许您将该信息与User
分开存储,并且您将在Contestant
中拥有一个ForeignKey
code> 模型引用User
,而Contestant
模型中的另一个ForeignKey
引用Team
。I would say your best bet is to create a
Contestant
model. You'll probably end up needing to store more information about a contestant that is team-specific but separate from a player (such as whether the contestant is a starter, the contestant's number, and so on). Creating aContestant
model allows you to store that information separate from theUser
, and you would have aForeignKey
in theContestant
model referencingUser
s, and anotherForeignKey
in theContestant
model referencingTeam
s.