如何过滤django中多对多字段的多个值的模型结果

时间:2012-02-23 09:52:58

标签: python django

我有以下型号:

class Group(models.Model):
    member = models.ManyToManyField(Player, through='GroupMember')
    name = models.CharField(max_length=20, unique=True)
    join_password = models.CharField(max_length=20)
    date_created = datetime.datetime.now()

    def __unicode__(self):
        return str(self.name)

class GroupMember(models.Model):
    member = models.ForeignKey(Player)
    group = models.ForeignKey(Group)
    rating = models.IntegerField(default=1500)
    played = models.IntegerField(default=0)
    wins = models.IntegerField(default=0)
    losses = models.IntegerField(default=0)
    experience = models.IntegerField(default=0)
    admin = models.BooleanField(default=0)

正如您所看到的,该组由成员组成。我想做的是给两个玩家我希望能够过滤包含这两个玩家的组,但我不确定如何进行这种类型的查询。

3 个答案:

答案 0 :(得分:35)

如果您的Player模型如下:

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

然后,您可以执行此查询:

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

大致转换为“查找所有名称与”Player1“和”Player2“匹配的玩家的群组

或者您可以单独获取player个对象:

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

答案 1 :(得分:20)

最简单的解决方案是:

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

请注意,您不能像这样使用__in过滤器,因为这会导致OR和返回组不包含两个播放器:

Group.objects.filter(member__in=[1, 2])

答案 2 :(得分:2)

对我来说__in没有用。我最终使用了complex Q lookup 它完美无缺,您可or过滤条件。像这样使用它:

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