简体   繁体   English

按 ManyToManyField Django 过滤对象

[英]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 *注意select_related中的组是由于另一个不相关的功能而存在的

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.我不知道我错过了什么/做错了什么。

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])假设你在Post模型中有一个author属性,它是外键User ,你可以使用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"所以基本上这个过滤器说:“寻找他们的作者在他们相关的朋友对象中拥有self.request.user的帖子”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM