1

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

1 Answer 1

4

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.

9
  • There is any reason to use followers_in? I think is ok to use followers=request.user.
    – allexiusw
    Jul 21, 2021 at 14:28
  • What if I need the filters working like filter1 AND filter2 ? Jul 21, 2021 at 17:12
  • Just list filter conditions separated by commas Post.objects.filter(author__profile__in=[logged_in_user.id], author__profile__followers__in=[logged_in_user.id]) @Arya Shesham Jul 21, 2021 at 17:22
  • I've tried Post.objects.filter(author__profile__in=[logged_in_user.id], author__profile__followers__in=[logged_in_user.id]) but its not working. @weAreStarDust Jul 21, 2021 at 17:50
  • You can try & operator instead | with Q objects. But my previous comment should work too. Jul 21, 2021 at 17:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.