我无法理解django-guardian函数get_objects_for_user的行为。我正在分配组对象权限,但get_objects_for_user似乎不存在这些权限。
>>> u = User.objects.get(username='angus')
>>> u.has_perm('news.change_news', n)
True
>>> from guardian.shortcuts import get_objects_for_user
>>> get_objects_for_user(u, (u'news.change_news', ))
[]
>>> get_objects_for_user(u, ('change_news'), klass=News)
[]
但文档似乎很清楚:
get_objects_for_user: (user, perms, klass=None, use_groups=True, any_perm=False)
Returns queryset of objects for which a given ``user`` has *all*
permissions present at ``perms``.
我甚至不知道从哪里开始调试。有什么建议吗?
更新
我的模型定义如下:
class News(models.Model):
departments = models.ManyToManyField(Department, blank=True, related_name='news', through='NewsDepartmentMembership')
research_groups = models.ManyToManyField(Group, blank=True, related_name='news', through='NewsGroupMembership')
people_involved = models.ManyToManyField(Person, blank=True, related_name='news')
related_news = models.ManyToManyField('News', blank=True)
title = models.CharField(_('Title'), max_length=255)
slug = models.SlugField(_('Slug'), unique_for_date='pub_date',)
excerpt = models.TextField(_('Excerpt'), blank=True)
content = models.TextField(_('Content'), blank=True)
is_published = models.BooleanField(_('Published'), default=False)
pub_date = models.DateTimeField(_('Publication date'), default=datetime.datetime.now)
is_feat = models.BooleanField(_('Featured'), default=False)
published = PublishedNewsManager()
objects = models.Manager()
featured = FeaturedNewsManager()
答案 0 :(得分:0)
像这样使用它: news = get_objects_for_user(u,('change_news'),klass = News)
编辑: 好吧,很容易找出问题所在:尝试使用guardian.shortcuts.get_perms(http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-perms)来查看用户和对象之间的权限是否真的存在。我前段时间遇到了类似的问题,如果我没记错的话,那就与用户超级用户有关。尝试为用户设置is_superuser false并查看has_perm是否仍返回true。
另外,如果可能的话,我建议你在项目变大时不要使用get_objects_for_user快捷方式。一旦在数据库中获得更多对象/权限,它的非常慢查询。
艾伦