Django使用__in做多条件OR查询时Post筛选结果为空的排查
问题原因
你现在的代码有两处核心错误:
- 逻辑条件错误:你要的是两个条件满足任意其一(或关系),但
filter(join_goal__in=xxx, creator__in=xxx)的逗号分隔是且关系,要求Post同时满足两个条件,不符合你的业务需求。 - 查询字段错误:
get_current_user_join_goal_follow函数里,你取的是FollowGoal表自身的主键uuid,而不是你要的关联的JoinGoal对象的id,导致join_goal__in匹配不到任何符合条件的Post,这也是你单独筛选关注目标条件时返回空的直接原因。
修复方案
1. 修正工具函数
首先修正关注目标列表的取值字段,同时不需要额外把UUID转成字符串,Django会自动匹配UUIDField类型,避免部分数据库下类型不匹配的问题:
def get_current_user_followee(request): current_user = request.user followee_list = list(FollowUser.objects.filter(follower=current_user).values_list('followee', flat=True)) followee_list.append(current_user.uuid) return followee_list def get_current_user_join_goal_follow(request): current_user = request.user # 这里取关联的join_goal字段,不是FollowGoal自身的uuid join_goal_list = list(FollowGoal.objects.filter(follower=current_user).values_list('join_goal', flat=True)) return join_goal_list
2. 用Q对象实现或条件查询
导入Django的Q对象,把两个查询条件用|(或运算符)拼接:
from django.db.models import Q @api_view(['GET']) def get_initial_posts(request, count): join_goal_list = get_current_user_join_goal_follow(request) followee_list = get_current_user_followee(request) posts = Post.objects.filter( Q(join_goal__in=join_goal_list) | Q(creator__in=followee_list) ).order_by('-uuid')[:count] serializer = full_post_data_serializer(posts) return Response(serializer.data, status=status.HTTP_200_OK)
可选性能优化
你不需要先把所有id查出来再做in查询,可以直接用子查询减少一次数据库交互,数据量大时性能提升明显:
from django.db.models import Q, Subquery @api_view(['GET']) def get_initial_posts(request, count): current_user = request.user # 关注的用户子查询 followee_subquery = FollowUser.objects.filter(follower=current_user).values('followee') # 关注的目标子查询 goal_subquery = FollowGoal.objects.filter(follower=current_user).values('join_goal') posts = Post.objects.filter( Q(join_goal__in=Subquery(goal_subquery)) | Q(creator__in=Subquery(followee_subquery)) | Q(creator=current_user) ).order_by('-uuid')[:count] serializer = full_post_data_serializer(posts) return Response(serializer.data, status=status.HTTP_200_OK)
内容的提问来源于stack exchange,提问作者user12314098
相关产品推荐
相关产品推荐

