views:

73

answers:

1

I have the concept of a team in my django app.

class Team(models.Model):
    name = models.CharField(max_length=200)
    #snip
    team_members = models.ManyToManyField(User)

I would like to fetch all teams the currently logged in user is member of. Something along the lines of

Team.objects.all().filter(request.user.id__in = team_members.all())

This obvious doesn't work. Does anyone have some suggestions on how to do such query without going directly to sql? I did look at the django documentation of "in" queries, but I couldn't find my use case there.

Many thanks! Nick.

+3  A: 

You don't need in here, Django handles that automatically in a ManyToMany lookup.

Also, you need to understand that the database fields must always be on the left of the lookup, as they are actually handled as parameters to a function.

What you actually want is very simple:

Team.objects.filter(team_members=request.user)
Daniel Roseman
Thank you very much for this tip, I must have missed this in the documentation, this is exactly what I need.
Nick