Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one-to-many relationships with django

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.

like image 287
crodjer Avatar asked Jan 21 '23 13:01

crodjer


2 Answers

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.

like image 180
Tomasz Zieliński Avatar answered Jan 25 '23 15:01

Tomasz Zieliński


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.

like image 26
Neo Avatar answered Jan 25 '23 14:01

Neo