[Answered ]-How to fetch self and friends posts on django model

1👍

You can filter the queryset with:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q

class PostListView(LoginRequiredMixin, ListView):
    model = PostForNewsFeed
    template_name = 'feed/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10
    count_hit = True
    slug_field = 'slug'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            Q(user_name=self.request.user) |
            Q(user_name__profile__friends__user=self.request.user)
        ).distinct()

    # …

We thus retrieve PostForNewsFeeds such that the user of the user_name is the logged in user (self.request.user), or if the user_name has the logged in user in the friends relation.


Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Leave a comment