JPC
JPC

Reputation: 8296

Django - filter ManyToManyField?

I'm not sure the best way to describe what it is that I'm trying to do so forgive my title.

I have two models, User and Group. Group contains field, members, which is a ManyToManyField referring to User.

Given a User, I want to find all of the Groups to which that user belongs.

My idea would be to do something like this:

groups = Group.objects.filter(user in members)

Something like that. Even though I realize that this isn't right

I tried reading through this link but couldn't figure out how to apply: http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

Thanks

EDIT:

Figured it out groups = Group.objects.filter(members__username=user.username)

Upvotes: 2

Views: 2099

Answers (2)

Tommaso Barbugli
Tommaso Barbugli

Reputation: 12031

If you have the user and you want to have his groups then start querying from it, not the way around ;)

Here's an example:

james = User.objects.get(pk= 123)
james_groups = james.group_set.all()

Upvotes: 2

XORcist
XORcist

Reputation: 4367

The most concise way is probably

groups = user1.group_set.all()

which gives you a queryset that is iterable.

Upvotes: 1

Related Questions