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

2024/11/20 6:21:39

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.

Answer

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)
https://en.xdnf.cn/q/26352.html

Related Q&A

Why is string comparison so fast in python?

I became curious to understand the internals of how string comparison works in python when I was solving the following example algorithm problem:Given two strings, return the length of the longest comm…

What is a namespace object?

import argparseparser = argparse.ArgumentParser(description=sort given numbers) parser.add_argument(-s, nargs = +, type = int) args = parser.parse_args() print(args)On command line when I run the comma…

How to get the element-wise mean of an ndarray

Id like to calculate element-wise average of numpy ndarray.In [56]: a = np.array([10, 20, 30])In [57]: b = np.array([30, 20, 20])In [58]: c = np.array([50, 20, 40])What I want:[30, 20, 30]Is there any …

Spark 1.4 increase maxResultSize memory

I am using Spark 1.4 for my research and struggling with the memory settings. My machine has 16GB of memory so no problem there since the size of my file is only 300MB. Although, when I try to convert …

Java abstract/interface design in Python

I have a number of classes which all share the same methods, only with different implementations. In Java, it would make sense to have each of these classes implement an interface or extend an abstract…

PyCharm - no tests were found?

Ive been getting na error in PyCharm and I cant figure out why Im getting it:No tests were foundThis is what I have for my point_test.py: import unittest import sys import ossys.path.insert(0, os.path.…

Does Python PIL resize maintain the aspect ratio?

Does PIL resize to the exact dimensions I give it no matter what? Or will it try to keep the aspect ratio if I give it something like the Image.ANTIALIAS argument?

How to scale images to screen size in Pygame

I was wondering how I would go about scaling the size of images in pygame projects to the resolution of the screen. For example, envisage the following scenario assuming windowed display mode for the t…

GridSearch for an estimator inside a OneVsRestClassifier

I want to perform GridSearchCV in a SVC model, but that uses the one-vs-all strategy. For the latter part, I can just do this:model_to_set = OneVsRestClassifier(SVC(kernel="poly"))My problem …

The Pythonic way of organizing modules and packages

I come from a background where I normally create one file per class. I organize common classes under directories as well. This practice is intuitive to me and it has been proven to be effective in C++,…