One-to-Many Relationships with django

I intend to create a unified system in which each team can contain several participants. The members are actually auth.User . Something like:

 Team: Contestant1 Contestant2 . . ContestantN 

Since the member is actually a user that I cannot change to have a foreignkey command in the team. What is the best way to achieve this?

How I did it:

  • Create a OneToOne profile for the user who points to the team.
  • Define the ManyToMany relationship between the user and the team where the user must be unique.

A pause

I am redesigning the structure of my application, so I will rephrase the question again

Thanks for your answers, I will review them and see if one of them fits.

+4
source share
4 answers

You can do it:

 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 participate in different teams, but if you do not want to allow this, you can add unique = True to Contestant.user .

+8
source

The best way would be to expand the functionality of the default accounts and create a new user model. A new user model may have a foreign key for the 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 "UserExtended" instead of the regular user.

+1
source

I would create a contestants field in the Team model as follows:

 from django.contrib.auth.models import User contestants = models.ManyToManyField(User) 

You cannot point unique=True to ManyToManyField. The good news is that he will not add the same opponent to the same team twice, so you won’t need to check if the participant is unique.

0
source

I would say that it is best to create a Contestant model. Most likely, you will need more information about the opponent, which depends on the team, but separately from the player (for example, whether the competitor is a starter, participant number, etc.). Creating a Contestant model allows you to store this information separately from User , and you will have a ForeignKey in the Contestant model referencing User s, and another ForeignKey in the Contestant model referencing Team s.

0
source

Source: https://habr.com/ru/post/1338673/


All Articles