Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

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

I have the following Model:

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)

As you can see the group is made up of members who are players. What I would like to do is given two players I would like to be able to filter the groups that contain both of these players but I am unsure how to do this type of query.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...