sly_Chandan
sly_Chandan

Reputation: 3515

How to fetch self and friends posts on django model

Profile.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.png', upload_to='profile_pics')
    slug = AutoSlugField(populate_from='user')
    bio = models.TextField(blank=True)
    friends = models.ManyToManyField("Profile", blank=True)

    def __str__(self):
        return str(self.user.username)

    def get_absolute_url(self):
        return "/users/{}".format(self.slug)




class PostListView(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_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        context.update({
        'popular_posts': PostForNewsFeed.objects.order_by('-hit_count_generic__hits')[:3],
        })
        if self.request.user.is_authenticated:
            liked = [i for i in PostForNewsFeed.objects.all() if Like.objects.filter(user = self.request.user, post=i)]
            context['liked_post'] = liked           
        return context


class PostForNewsFeed(models.Model):
    title = models.CharField(max_length=100, blank=True)
    description = models.CharField(max_length=255, blank=True)
    slug = models.SlugField(unique=True, max_length=100, blank=True)
    pic = models.ImageField(upload_to='path/to/img', default=None,blank=True)
    youtubeVideo = models.CharField(max_length=200, null=True, blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    user_name = models.ForeignKey(User, on_delete=models.CASCADE)
    tags = models.CharField(max_length=100, blank=True)
    hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
     related_query_name='hit_count_generic_relation2', default=1)

How to fetch Posts from self and friends posts via orm query?

path('', PostListView.as_view(), name='home2'),

Upvotes: 1

Views: 60

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

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].

Upvotes: 1

Related Questions