Saqib Ali
Saqib Ali

Reputation: 12605

How to use Q objects to check if any members of arbitrary-length list are in Many-To-Many Relationship?

Suppose I have the following Django models:

class myClass1(models.Model):
    myField1 = models.IntegerField()     


class myClass2(models.Model):
    myLocalClass1 = models.ManyToManyField(myClass1)     

Furthermore, suppose I have a list of unique myClass1s:

a = myClass1(myField=1)
b = myClass1(myField=2)
c = myClass1(myField=3)
myTargetList = [a, b, c]

Now, I would like to write a Django query using Q objects such that it returns all the myClass2s that have any member of myTargetList as myLocalClass1. Furthermore, I don't know the exact size of myTargetList in advance.

How should I do it? This obviously won't work:

myClass2.objects.filter(Q(myLocalClass1__in=myTargetList))

Upvotes: 0

Views: 76

Answers (2)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

You nearly have it, you don't need Q objects, you can just use a combination of in and values_list:

l = myClass1.objects.filter(myField__in=[1, 2, 3]).values_list("id", flat=True)
myClass2.objects.filter(myLocalClass1__pk__in=l) 

Upvotes: 1

karthikr
karthikr

Reputation: 99660

You can do this:

myclass1_qs = myClass1.objects.filter(myField__in=[1, 2, 3])
myclass2_qs = myClass2.objects.filter(myLocalClass1__in=myclass1_qs).distinct()

Or Here is a one liner,

myclass2_qs = myClass2.objects.filter(myLocalClass1__myField__in=[1, 2, 3]).distinct() 

Upvotes: 1

Related Questions