Python – The intersection of two query sets in django

The intersection of two query sets in django… here is a solution to the problem.

The intersection of two query sets in django

I can’t do AND on both query sets. Such as q1 and q2. I get empty sets, I don’t know why. I have tested this with the simplest case. I’m using Django 1.1.1

I basically have objects like this:

item1
   name="Joe"
   color = "blue"
item2
   name="Jim"
   color = "blue"
   color = "white"
item3
   name="John"
   color = "red"
   color = "white"

Is there anything weird about building many-to-many relationships? Or am I missing something?

queryset1 = Item.objects.filter(color="blue")
This gives (item1, item2).

queryset2 = Item.objects.filter(color="white")
This gives (item2, item3).

queryset1 & queryset2 give me empty set []
The OR operator works fine (I’m using “|“)

Why is this?

Solution

qs = Item.objects.filter(color__in=['blue','white'])

Related Problems and Solutions