from guardian.shortcuts import get_objects_for_user
但是
呢?from guardian.shortcuts import get_users_for_object
谢谢。
实际上有一个快捷方式
http://django-guardian.readthedocs.io/en/stable/api/guardian.shortcuts.html get-users-with-perms
>>> from django.contrib.flatpages.models import FlatPage
>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import assign_perm, get_users_with_perms
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
>>> assign_perm('change_flatpage', joe, page)
>>>
>>> get_users_with_perms(page)
[<User: joe>]
>>>
>>> get_users_with_perms(page, attach_perms=True)
{<User: joe>: [u'change_flatpage']}
这是我的解决方法。这是模型方法。你可以把它封装在mixin中。
def get_users_with_perm(self, permission):
'''
Returns list of users(worn:not QuerySet) with specific permission for this object
:param permission: permission string
'''
anyperm = get_users_with_perms(self, attach_perms=True)
result = []
for user, perms in anyperm.iteritems():
if permission in perms: result.append(user)
return result
看起来不错:https://github.com/lukaszb/django-guardian/blob/master/guardian/shortcuts.py#L214
>>> from django.contrib.flatpages.models import FlatPage
>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import assign_perm, get_users_with_perms
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
>>> assign_perm('change_flatpage', joe, page)
>>>
>>> get_users_with_perms(page)
[<User: joe>]
>>>
>>> get_users_with_perms(page, attach_perms=True)
{<User: joe>: [u'change_flatpage']}
我使用内置的get_users_with_perms()快捷方式解决了这个问题,然后使用python字典推导返回对给定对象具有特定权限的用户对象列表。
from django.contrib.flatpages.models import FlatPage
from django.contrib.auth.models import User
from guardian.shortcuts import assign_perm, get_users_with_perms
创建一个page对象并赋予User 'Joe' change_flatpage权限
page = FlatPage.objects.create(title='Some page', path='/some/page/')
joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
assign_perm('change_flatpage', joe, page)
使用Guardian查找对特定页面对象具有任何权限的用户
perms = get_users_with_perms(page, attach_perms=True)
使用python字典推导返回包含特定权限的新用户列表
perm_name = "change_flatpage"
change_flatpage_user_list = [ k for k, v in perms.items() if perm_name in v ]