Django - Team/User relationships

Viewed 464

I'm at a loss... I'm just learning Django and I am really rather confused about how to make a field work the way I would like it to.

I understand that Django has a native "Groups" model. However, I am looking to build my own teams model for customization and practice.

Here is my models.py file for my Users app:

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


class Team(models.Model):
    members = models.ManyToManyField(User)


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    admin = models.BooleanField("Admin Status")

Here's where I'm confused. I would like to be able to call the team that the user is part of directly from User.Profile. So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.

A potential problem I can see is that, currently, I can assign a user to multiple teams. This doesn't bother me, perhaps I can have a Profile model field that automatically populates with a list of all the teams that the user is associated with. Regardless, I can't figure out what type of field I would need to use, or how to do this.

Does that make sense?

3 Answers

A potential problem I can see is that, currently, I can assign a user to multiple teams.

Indeed, you can however easily retrieve the Teams the myprofile object is a member of with:

Team.objects.filter(members__profile=myprofile)

You thus can make a property for the Profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    admin = models.BooleanField("Admin Status")
    
    @property
    def teams(self):
        return Team.objects.filter(
            members__profile=self
        )

Then you thus access the Teams of a myprofile with myprofile.teams.

So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.

From my limited knowledge of database, you can add a name field to your Team model.

Keeping in mind your requirement as mentioned in question, i would suggest you to use django reverse relations to get all the teams the profile is associated with

user_teams = User.objects.get(id='user_id').profile_set.all()[0].team_set.all()

to know more about django ORM reverse relation, here is a very short article

Related