Implementing a model for "teams" in django

I want to implement a command function in django 1.8. (Team like a sports team)

Each user can join one team at a time, and a team can contain many users. Now I am not sure how to define my models.py

I started with this core, but now I'm not sure how to make the Team ↔ User connection

from django.db import models

class Team(models.Model):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(max_length=1024)
    logo = models.ImageField()

from django.contrib.auth.models import User

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

      

Now am I creating a second class user_team or am I just adding the command as a foreign key to the user? (and if so, how do I need it?)

Thank,

Wegi

// edit: I added the code below. Will this player model be sufficient to define attitudes?

+3


source to share


2 answers


In this case, I still propose an alternative, using a ManyToMany field , with an intermediate model and a model manager.

The 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(model.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    other_fields = #...

    objects = PlayerManager()

      

Using:

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

      



Then you should be able to get the command associated with the user like:

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

      

Note . I have not tested the code, so please correct me if I make a mistake.

The reason I prefer this way is to abstract away the database logic in the application. Therefore, in the future, if there is a need to allow User

merging of multiple commands, you can simply change the application logic to allow this through the manager.

+5


source


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 by adding Teams as a ManyToMany field inside the Teams class because I'm not sure if I need to add any field to the Player during development.

Thanks everyone for your help.

+1


source







All Articles