Saqib Ali
Saqib Ali

Reputation: 12605

How to use Q objects to test list membership?

With normal Django querysets, if I want to retrieve all the myObjects whose "a" attribute is 1, 2 or 3, I would do the following:

myObjects.objects.filter(a_in=[1,2,3])

But I would like to do this using the Q objects. How would I write the equivalent query with Q objects?

Upvotes: 0

Views: 58

Answers (3)

Rao
Rao

Reputation: 892

q = Q(a__in=[1,2,3])
#q = Q(('a__in', [1,2,3]))
myObjects.objects.filter(q)

Edit: Bah never mind, tuple not needed.

Upvotes: 1

Silwest
Silwest

Reputation: 1620

It should look like this:

myObjects.objects.filter(Q(a = 1) | Q( a = 2) | Q( a = 3))

I don't know why you want to do that but you can also do

myObjects.objects.filter(Q(a__in=[1,2,3])

Upvotes: 2

kirelagin
kirelagin

Reputation: 13616

It works right away.

Q(a__in=[1, 2, 3])

Probably your issue is that you were using a single underscore instead of two.

Upvotes: 2

Related Questions