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

前端 未结 3 1042
感情败类
感情败类 2020-12-13 18:35

I have the following Model:

class Group(models.Model):
    member = models.ManyToManyField(Player, through=\'GroupMember\')
    name = models.CharField(max_l         


        
相关标签:
3条回答
  • 2020-12-13 18:43

    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)
    
    0 讨论(0)
  • 2020-12-13 19:01

    The easiest solution for you will be:

    p1 = Player.objects.get(id=1)
    p2 = Player.objects.get(id=2)
    groups = Group.objects.filter(member=p1).filter(member=p2)
    

    Note that you can't use the __in filter like this because this will result in an OR and return groups that don't contain both players:

    Group.objects.filter(member__in=[1, 2])
    
    0 讨论(0)
  • 2020-12-13 19:02

    For me __in did not work. I ended up using the complex Q lookup which works perfectly and you can or filter conditions with. Use it like this:

    from django.db.models import Q
    
    p1 = Player.objects.get(name='Player1')
    p2 = Player.objects.get(name='Player2')
    querySet = Group.objects.filter(Q(member=p1) | Q(member=p2))
    
    0 讨论(0)
提交回复
热议问题