Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Team/User relationships

Tags:

python

django

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?

like image 265
YangTegap Avatar asked Feb 13 '26 02:02

YangTegap


1 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.

like image 74
Willem Van Onsem Avatar answered Feb 15 '26 15:02

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!