如何获取用户在 django Guardian 中具有特定权限的所有对象? [英] How can I get all objects a user has specific permissions to in django guardian?

查看:36
本文介绍了如何获取用户在 django Guardian 中具有特定权限的所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在对所有对象进行非常笨拙的循环,但这会变慢:

I am currently doing a really clumsy loop over all the objects but that is going to get slow:

videos = Video.objects.all()
video_list = []
for video in videos:
    checker = ObjectPermissionChecker(request.user)
    if checker.has_perm('view_video', video):
        video_list.append(video)

我认为必须有一种方法可以获取该用户对其具有权限的所有对象.

I figure there must be a way of just getting all the objects for which this user has permissions.

推荐答案

几天前更新了名为get_objects_for_user"的新快捷功能.如果您使用旧版本的 Guardian 且无法更新,您只需从那里复制代码即可.

a few days ago there were update with new shortcut function called "get_objects_for_user". If you use older version of guardian and cannot update, you can simply copy codes from there.

from guardian.shortcuts import get_objects_for_user
...
videos = get_objects_for_user(request.user, "view_video", Video.objects.all())

它总是做 3 次查询.如果您将use_groups"参数指定为 False,则执行 2 个查询,但是返回的查询集将不包含用户组具有权限的对象.如果需要,您还可以指定代号列表,而不是单个权限.在这里阅读更多内容.

It always do 3 queries. If you specify "use_groups" parameter to False, then 2 queries are performed however returned queryset wouldn't contain objects for which users' groups have permissions. You may also specify list of codenames, rather than single permission if needed. Read more here.

这篇关于如何获取用户在 django Guardian 中具有特定权限的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆