I intend to create a teaming system, where each team may contain multiple contestants. The co开发者_运维问答ntestants 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.You can do this:
class Team(models.Model):
contestants = models.ManyToManyField(User, through='Contestant')
class Contestant(models.Model):
team = models.ForeignKey(Team)
user = models.ForeignKey(User)
[here go Contestant data fields]
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.
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.
class UserExtended(models.Model):
def __unicode__(self):
return self.user.username
user = models.OneToOneField(User, unique=True)
team = models.ForeignKey(Team)
User.profile = property(lambda u: UserExtended.objects.get_or_create(user=u)[0])
Now you can use the "UserExtended" in place of normal User.
I would create a contestants
field on the Team
model like so:
from django.contrib.auth.models import User
contestants = models.ManyToManyField(User)
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.
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 a Contestant
model allows you to store that information separate from the User
, and you would have a ForeignKey
in the Contestant
model referencing User
s, and another ForeignKey
in the Contestant
model referencing Team
s.
精彩评论