其他分享
首页 > 其他分享> > django Q 查询用法实例

django Q 查询用法实例

作者:互联网

需求场景

当前存在某场景如 (A and not B) or C

需求实现

方式一

直接用 Q 串联, 写入在条件中通过组合实现 与或关系

xxx.object.filter(Q(Q(A), ~Q(B)) | Q(C))

方式二

Q 构造, 与或关系通过 .add 引入, 实现更友好的代码可读性

q_1 = Q(A)
q_2 = ~Q(B)
q_3 = Q(C)
q = Q()
q.add(q_1, "and")
q.add(q_2, "and")
q.add(q_3, "or")
queryset = xxx.objects.filter(q)

场景实例

user_name = request.query_params.get("username", request.user.u_name or request.user.username)
q_1 = Q(cur_nodes_a__operator__icontains=user_name)
q_2 = ~Q(cur_nodes_a__status__exact="pass")
q_3 = Q(o_logs_a__operator=user_name)
q = Q()
q.add(q_1, "and")
q.add(q_2, "and")
q.add(q_3, "or")
queryset = models.AutoOrder.objects.filter(q)
print(models.AutoOrder.objects.filter(q).query.__str__())
# queryset = models.AutoOrder.objects.filter(Q(Q(cur_nodes_a__operator__icontains=user_name),
#                                         ~Q(cur_nodes_a__status__exact="pass")) |
#                                       Q(o_logs_a__operator=user_name))
kwargs["queryset"] = queryset.distinct()

 

标签:__,name,queryset,用法,filter,add,实例,user,django
来源: https://www.cnblogs.com/shijieli/p/15900543.html