Chaining multiple filters() in Django having different lists

3.3k views Asked by At

I've been trying to use two different filter conditions having 2 different set of lists. Here, filter(condt.1) is working and filter(condt.2) is working; but when I use filter(condt.1).filter(condt.2) it's working differently i.e. not working in the way I had assumed. Here is my situation:

  1. This one is working properly: posts = Post.objects.filter(author__profile__in=[logged_in_user.id])

  2. This one is also working properly: posts = Post.objects.filter(author__profile__followers__in=[logged_in_user.id])

But I am not getting the way to combine these two filters in one. Here is what I've tried:

logged_in_user = request.user
posts = Post.objects.filter(author__profile__in=[logged_in_user.id]).filter(author__profile__followers__in=[logged_in_user.id])
1

There are 1 answers

9
weAreStarsDust On

If you need this filters working like filter1 OR filter2, you can use Q objects with | operator

from django.db.models import Q

logged_in_user = request.user
posts = Post.objects.filter(
    Q(author__profile__in=[logged_in_user.id]) | 
    Q(author__profile__followers__in=[logged_in_user.id])
)

In your example django gives you result matching both filters at the same time.