Cheeseburger145
Cheeseburger145

Reputation: 63

Filter a queryset by a list of users and request.user at the same time

I would like to create a queryset containing posts from both a list of 'friends' and 'request.user'.

So far I can only filter posts by friends using posts = Post.objects.filter(user__in=friends). I tried to do posts = Post.objects.filter(user__in=friends).filter(user=request.user) but this returns an empty queryset.

I can't figure out how to filter 'posts' using both parameters at the same time.

Any suggestions would be much appreciated, cheers.

Upvotes: 1

Views: 253

Answers (2)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You can use the Q objects like this

from django.db.models import Q

Post.objects.filter(Q(user__in=friends)|Q(user=request.user))

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

Here you filter in such way that the user should be in the list of friends and it should be request.user. Which will likely not work.

You can here use Q-objects [Django-doc] to make a logical or:

from django.db.models import Q

Post.objects.filter(Q(user__in=friends) | Q(user=request.user))

Upvotes: 1

Related Questions