希望你能幫助我。
我正在嘗試運行以下 - 僅針對當前請求用戶。但它會收回所有用戶的資料。
你能幫我弄清楚為什么會這樣嗎?
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
''')
uj5u.com熱心網友回復:
正如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注入[維基]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352967.html
上一篇:Django動態url引數
