How to filter model results for multiple values for a many to many field in django

If your Player model looks like this:

class Player(models.Model):
    name = models.CharField(max_length=200)

Then, you can execute this query:

Group.objects.filter(player__name__in=['Player1','Player2'])

Which roughly translates to “find all groups that have players whose names match ‘Player1’ and ‘Player2′”

Or you can fetch the player objects individually:

p1 = Player.objects.get(name="Player1")
p2 = Player.objects.get(name="Player2")
groups = Group.objects.filter(player=p1).filter(player=p2)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)