简体   繁体   English

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

[英]How can I get all objects a user has specific permissions to in 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. 我认为必须有一种方法来获取该用户拥有权限的所有对象。

a few days ago there were update with new shortcut function called "get_objects_for_user". 几天前,有一个名为“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())

It always do 3 queries. 它总是做3个查询。 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. 如果将“use_groups”参数指定为False,则会执行2个查询,但返回的查询集将不包含用户组具有权限的对象。 You may also specify list of codenames, rather than single permission if needed. 您还可以指定代码列表,而不是根据需要指定单个权限。 Read more here . 在这里阅读更多

You know that you are creating a new instance of ObjectPermissionChecker in each loop while you don't have to do that , and i will suggest to do something like this which can be more syntactically sugar and maybe can give you more speed 你知道你在每个循环中创建一个新的ObjectPermissionChecker实例而你不必这样做,我建议你做一些这样的事情,它可以在语法上更加糖,也许可以给你更多的速度

checker = ObjectPermissionChecker(request.user)

videos = Video.objects.all()

video_list = [video for video in videos if checker.has_perm('view_video', video)]

For your question you can use django-object-permissions look here for more detail about how to use. 对于您的问题,您可以使用django-object-permissions查看此处了解有关如何使用的更多详细信息。

If you want to speed up drastically why not jus ask the database to pull only the objects you're interested in, 如果你想大大加快速度,为什么不要求数据库只提取你感兴趣的对象,

content_type = ContentType.objects.get_for_model(Video)
perm = Permissions.objects.get(codename='view_video'.split('.')[-1])

objs = set(
    UserObjectPermissions.objects.filter(user=user, permission=perm, content_type=content_type)
)

# and if you want to include groups
objs.update(
    set(
         GroupObjectPermissions.objects.filter(group__user=user, permission=perm, content_type=content_type)
    )
)

This should get you all user objects which the user has permission to through both their user and group. 这应该为您提供用户有权通过其用户和组访问的所有用户对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM