Search code examples
pythondjangopinax

How to perform a query in django that selects all projects where I am a team member of?


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.


Solution

  • 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)
    

    or

    request.user.team_set.all()