简体   繁体   English

同时通过用户列表和 request.user 过滤查询集

[英]Filter a queryset by a list of users and request.user at the same time

I would like to create a queryset containing posts from both a list of 'friends' and 'request.user'.我想创建一个查询集,其中包含来自“朋友”和“request.user”列表的帖子。

So far I can only filter posts by friends using posts = Post.objects.filter(user__in=friends) .到目前为止,我只能使用posts = Post.objects.filter(user__in=friends)过滤朋友的posts = Post.objects.filter(user__in=friends) I tried to do posts = Post.objects.filter(user__in=friends).filter(user=request.user) but this returns an empty queryset.我试图做posts = Post.objects.filter(user__in=friends).filter(user=request.user)但这返回一个空的查询集。

I can't figure out how to filter 'posts' using both parameters at the same time.我不知道如何同时使用这两个参数过滤“帖子”。

Any suggestions would be much appreciated, cheers.任何建议将不胜感激,干杯。

Here you filter in such way that the user should be in the list of friends and it should be request.user .在这里,您以这样的方式过滤, user应该在朋友列表中,并且应该是request.user Which will likely not work.这可能不起作用。

You can here use Q -objects [Django-doc] to make a logical or:您可以在这里使用Q -objects [Django-doc]进行逻辑或:

from django.db.models import Q

Post.objects.filter(Q(user__in=friends) | Q(user=request.user))

You can use the Q objects like this您可以像这样使用Q 对象

from django.db.models import Q

Post.objects.filter(Q(user__in=friends)|Q(user=request.user))

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

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