Abdul Rehman
Abdul Rehman

Reputation: 5654

Django 2 Many to Many relationships

I'm working on a project using Python(3.7) and Django(2.1) in which I need to build a relationship between users and organizations.

I'm using the default Django User model and a profile model to add extra information to users.

Many users can join an organization and an Organization can have many members, a user can create an Organization, these behaviors I need to implement, according to my understanding we need to build a ManyToMany relationship for Organizations model, but don know how to use this relationship to display the information, e.g display a user's organizations on his profile page.

Here are my models:

class Organization(models.Model):
    name = models.CharField(max_length=255, blank=False)
    users = models.ManyToManyField(User, related_name='members', null=True)

    def __str__(self):
        return self.name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')
    goals = MultiSelectField(choices=goals_choices, default='')

    def __str__(self):
        return f'{self.user.username} Profile'

Upvotes: 0

Views: 133

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

You can get all organizations of a particular user by:

my_user.members.all()

If you want to access from profile:

my_profile.user.members.all()

But I would suggest to remove related_name or rename it. If you remove it you can access all user organizations as:

my_user.organization_set.all()
my_profile.user.organization_set.all()

For organization you can get all users by:

my_org.users.all()

Upvotes: 1

Related Questions