[Django]-How can I do AND lookups with Q objects when using repeated arguments instead of chaining filters?

0👍

I believe this should work:

Blog.objects.annotate(author2=author).filter(Q(author__name='bob') & Q(author2__name='mary'))

0👍

So, it seems that you just can’t use Q objects to AND the same argument, even if it’s in a M2M relationship. I found a solution on Reddit to basically construct multiple queries with chained filters and then OR them together, eliminating the need for Q objects:

b1 = Blog.objects.filter(authors__name='bob').filter(authors__name='mary')
b2 = Blog.objects.filter(authors__name='steve')
qs = b1 | b2

Leave a comment