Home > OS >  Relation between two models in Django
Relation between two models in Django

Time:03-17

It seems like a trivial question but I am new to Django. I have two models user and competition.

The user can create and join one or many competition. How to specify this relation as the user can be the owner of competition/s and can be a participant in one or more competition.

CodePudding user response:

I Assume You have two tables User and Competition:

then in competition you can user models.ManyToManyField

Example

class User:
   ...

class Competition:
   ...
   creator = models.ForeignKey(User)
   participents = models.ManyToManyField(User)

CodePudding user response:

To add to the answer above, you may explicitly define the intermediary entity of User and Competition if you would like to customize it. It would look something like this:

class User(models.Model):
   ...
   name = models.CharField(max_length=50)

class Competition(models.Model):
   ...
   creator = models.ForeignKey(User)
   participants = models.ManyToManyField(
      User,
      through="Participants",
      )

class Participants(models.Model):
   TEAM_COLOR_CHOICES = [
      (1,'White'),
      (2, 'Red'),
      (3, 'Blue')
   ]
   user = models.ForeignKey("User", on_delete=models.CASCADE)
   competition = models.ForeignKey("Competition", on_delete=models.CASCADE)
   teamcolor = models.PositiveSmallIntegerField(default=1, choices=TEAM_COLOR_CHOICES )

You can also display attributes within the intermediary and its parents on an HTML template with:

{% for participant in context.participants_set.all %}
{{ participant.user.name }}
{{ participant.teamcolor }}
...
{% endfor %}
  • Related