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

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

问题描述

我正在对所有的对象做一个非常笨拙的循环,但是会变慢:

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 。如果您使用较旧版本的监护人,无法更新,您可以直接从中复制代码。

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监护人如何获得用户具有特定权限的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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