0

Suppose I have the following Django models:

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


class myObj2(models.Model):
    myLocalObj1 = models.ManyToManyField(myObj1)     

Furthermore, suppose I have a list of unique myObj1s:

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

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

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

myObj2.objects.filter(Q(myLocalObj1__in=myTargetList))
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

1

EDIT: To make this a little more in line with what you are looking for (although I would not necessarily recommend doing things this way), you could:

vallist=[]
for b in myTargetList:
    vallist.append(b.myField)

myObj2.objects.filter(myLocalObj1__in=myObj1.objects.filter(myField__in=vallist))

This is available in the Django docs here: https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

Titus P
  • 959
  • 1
  • 7
  • 16
  • That didn't work. It's not valid python syntax. And even if it was, it does not produce the right answer. – Saqib Ali Jun 06 '13 at 15:56
  • Hmm, maybe my version of python is a bit different, using 2.5 it worked fine. I will edit my answer and maybe get something a little more inline with what you are looking for – Titus P Jun 07 '13 at 16:56