[Django]-Implementing a model for "teams" in django

9👍

For this use case, I will still suggest an alternative using a ManyToMany field, with an intermediate model and model manager.

A quick sample structure looks like this:

from django.db import models
from django.contrib.auth.models import User


class Team(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(max_length=1024)
    logo = models.ImageField()
    players = models.ManyToManyField(User, through='Player')


class PlayerManager(models.Manager):
    use_for_related_fields = True

    def add_player(self, user, team):
        # ... your code here ...

    def remove_player(self, user, team):
        # ... your code here ...

    def trasnfer_player(self, user, team):
        # ... your code here ...


class Player(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    other_fields = #...

    objects = PlayerManager()

Usage:

Player.objects.add_player(user, team, *other_fields)

You will then be able to get User related Team, for example:

team_with_user = Team.objects.filter(players__name="hello")
user_in_team = User.objects.filter(team__name="world")

Note: I haven’t tested the code, so please correct me if I make any mistake above.

The reason why I prefer this way is to abstract away your database logic into application. So in future if there is a need for allowing User joining multiple teams, you can just change the application logic to allow it through the manager.

👤Anzel

2👍

As suggested by @aumo I solved the problem by adding a user profile model like this:

from django.contrib.auth.models import User

class Player(models.Model):
    user = models.OneToOneField(User)
    team = models.ForeignKey('Team')

I chose this solution over adding teams as a ManyToMany field inside the Teams class because I am not sure if any more field need to be added to the Player during development.

Thanks to everybody for your help.

👤WeGi

Leave a comment