jeremy_lord
jeremy_lord

Reputation: 469

Filter objects by ManyToManyField Django

I have a friends feature on my website, and I want the homescreen to be posts filtered by the users the current user follows.

Here is the relevant model

class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,max_length=30)
    friends = models.ManyToManyField(User,blank=True,related_name='user_connections')

And the relevant view

class PostViewList(HitCountDetailView,SelectRelatedMixin,ListView):
    model = Post    
    count_hit = True
    template_name = 'mainapp/list.html'
    select_related = ("user","group",)
    paginate_by = 5
    context_object_name = 'posts'
    queryset = models.Post.objects.all()

    def get_queryset(self):
        # return Post.objects.filter(author__friends__friend__id=self.request.user.id)
        qs = super().get_queryset()
        select_related = ("user","group",)
        # user = self.user
        return qs.filter(Q(friend__author=self.kwargs['post.author']))

*note that the group in the select_related is there because of another unrelated feature

As you can see, I have tried to filter out posts, but it doesn't work.

I don't know what I am missing/doing wrong.

Upvotes: 1

Views: 93

Answers (1)

Sajad
Sajad

Reputation: 524

Assuming you have an author attribute in Post model, which is foreign keyed to User, you can use filter(author__user_connections__in=[self.request.user])
So basically this filter says: "look for the Posts that their authors have self.request.user in their related friend objects"

Upvotes: 2

Related Questions