python-3.x - 将 Django 数据限制为当前用户
问题描述
希望你能帮助我。
我正在尝试运行以下内容 - 仅适用于当前请求用户。但它会为所有用户拉回数据。
你能帮我弄清楚这是为什么吗?
open_tasks = skills.objects.filter(creator=request.user).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 group by category, status)s
group by id, status)p
group by id)j
''')
解决方案
正如raw(…)
[Django-doc]上的 Django 文档所说:
raw()
总是触发一个新的查询并且不考虑以前的过滤。因此,通常应该从新实例Manager
或从新QuerySet
实例调用它。
因此,您应该在原始查询中包含用户过滤:
open_tasks = skills.objects.filter(creator=request.user).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_id=%s
GROUP BY category, status)s
group by id, status)p
group by id)j''',
[request.user.pk]
)
在这里,我们使用可以传递给查询 [Django-doc] 的参数。不应使用数据格式化 SQL 字符串,因为这可能导致SQL 注入[wiki]。
推荐阅读
- javascript - JavaScript-SVG 事件对应是如何工作的?
- javascript - Javascript SVG根据路径方向控制XY
- algorithm - O(n) 中的 Frechet 距离
- python - 将组的所有用户添加为模型字段中的选项
- sql - 在给定页面数量的情况下处理基于值的分页
- angularjs - 如何在 angularJs 表达式中使用该正则表达式?
- ios - 默认突出显示表格视图单元格未显示
- angular - Angular Material Stepper 和 Stackblitz 示例的问题
- lag - 敌人在屏幕上时停止移动,但会在屏幕外起作用
- c++-winrt - 为什么变量声明会引发异常?