2👍
✅
Instead of pulling all posts, then removing private ones that do not belong to the user, pull all public posts and add private posts that the user can see.
from django.db.models import Q
if request.user.is_authenticated():
# Return public (private=False), and private posts of the user
visible_posts = Post.objects.filter(Q(private=False) |
Q(private=True, user=request.user))
else:
# Only return public posts
visible_posts = Post.objects.filter(private=False)
If you don’t have an authenticated user, just
The Q
allows you form more complex queries, if you’re not familiar, you can read above query as “public posts or private posts belonging to the user”
Source:stackexchange.com