将 Django 数据限制为当前用户

Limit Django data to current user

希望你能帮助我。

我正在尝试 运行 以下内容 - 仅针对当前提出请求的用户。但它会拉回所有用户的数据。

你能帮我弄清楚这是为什么吗?

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() always triggers a new query and doesn’t account for previous filtering. As such, it should generally be called from the Manager or from a fresh QuerySet instance.

因此,您应该在原始查询中包含用户过滤:

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
            <strong>WHERE creator_id=%s</strong>
            GROUP BY category, status)s
            group by id, status)p
            group by id)j''',
        [<strong>request.user.pk</strong>]
    )

这里我们利用了parameters that we can pass to the query [Django-doc]. One should not format the SQL string with the data, since that can result in SQL injection [wiki].