且构网

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

django监护人如何获得用户具有特定权限的所有对象?

更新时间:2023-11-30 10:31:58

几天前有更新新的快捷方式函数叫做get_objects_for_user 。如果您使用较旧版本的监护人,无法更新,您可以直接从中复制代码。

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.