且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取用户在 django Guardian 中具有特定权限的所有对象?

更新时间:2023-02-12 21:42:06

几天前更新了名为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.