Search code examples
pythondjangodjango-q

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?


Solution

  • 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])