You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django限定当前用户查询失效:filter过滤后raw查询仍返回所有用户数据

问题成因
  • Django ORM的raw()方法会直接执行传入的原生SQL语句,忽略此前链式调用中添加的所有ORM查询条件,因此你代码中写的filter(creator=request.user)完全没有生效。
  • 你编写的原生SQL内部也没有添加用户过滤逻辑,最内层查询直接对voximisa_skills全表做聚合计算,自然会返回所有用户的相关数据。
修复方案

方案1:修改原生SQL添加用户过滤(适合快速修复现有逻辑)

使用raw()的参数化传参能力添加用户过滤条件,避免SQL注入风险,修改后代码如下:

open_tasks = skills.objects.raw('''
            SELECT *, round(((closed_points)/(open_points+closed_points)*100),2) as points_pct,
            round(((closed_count)/(open_count+closed_count)*100),2) as closed_pct from (
            SELECT id, sum(open_points) as open_points, sum(closed_points) as closed_points, sum(open_count) as open_count, sum(closed_count) as closed_count
            from (
            SELECT id, 
            case when status = 'open' then sum(points) end as open_points,
            case when status <> 'open' then sum(points) end as closed_points,
            case when status = 'open' then sum(count) end as open_count,
            case when status <> 'open' then sum(count) end as closed_count
            from (
            SELECT category as id, status, sum(cast(points as int)) as points, count(*) as count 
            FROM voximisa_skills where creator = %s group by category, status)s
            group by id, status)p
            group by id)j
            ''', params=[request.user.id])

注意:如果你的creator字段存储的不是用户ID,可将request.user.id替换为匹配的字段值即可。

方案2:改用ORM聚合实现

如果不想写原生SQL,可以使用Django ORM的annotate、Case、When等聚合函数实现相同逻辑,天然支持filter(creator=request.user)的过滤条件,可读性和安全性更高。

内容的提问来源于stack exchange,提问作者kikee1222

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:15:04