Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django / User access in ManyToMany field

I am making a django app using the User class from django.contrib.auth.models.

I have defined a model, called a group with a M2M relationship to users. I have difficulty retrieving the groups a given user belongs to.

Here's the group definition:

class group(models.Model):
    user = models.ForeignKey(User,related_name = 'owner') # the owner
    name = models.CharField(max_length=100) # name of the group 

    # members of the group
    members = models.ManyToManyField(User,related_name = 'member')

    def __unicode__(self):
        return str(self.name)

I would like to retrieve the groups for which the user belongs to the members field of the groups.

Here is the command that fails, trying to retrieve the groups that a particular user belongs to - I am not sure why - could you let me know ? (user is a User instance)

user_groups = user.group_set.all()

The error I get is:

 'User' object has no attribute 'group_set'

What's wrong here?

SOLUTION

I eventually found the solution. I had to make the query with the related_name, so here it is:

groups_member = user.member.all()
like image 392
mikolune Avatar asked Apr 13 '12 20:04

mikolune


1 Answers

Because the many-to-many relation is through the members property, and this property has the related_name attribute, the correct syntax is:

user_groups = user.member.all()

( Without the related name attribute, it would be user_groups = user.members_set.all() )

And the reverse relation is:

group_users = group.members.all()
like image 67
dani herrera Avatar answered Oct 31 '22 22:10

dani herrera