5

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()
4

1 回答 1

10

因为多对多关系是通过members属性,而这个属性有related_name属性,所以正确的语法是:

user_groups = user.member.all()

(如果没有相关的名称属性,它将是user_groups = user.members_set.all()

而相反的关系是:

group_users = group.members.all()
于 2012-04-13T21:09:25.707 回答