【问题标题】:hierarchal permission on same model同一模型的分层权限
【发布时间】:2014-03-21 10:59:52
【问题描述】:

抱歉,我找不到合适的标题,如果您理解问题,请编辑标题。

我想实现 4 级层次结构(django 组):国家经理、国家经理、城市经理和外勤人员。

一个用户一次只能属于一个组,任何用户都可以添加潜在客户。

我有一个名为 Lead 的模型,我想实现以下层次结构:

"User of higher level (say State-Manager) can view leads added by him and and all entries added by users of lower level (say City-Manager and Field Staff) but can not view entries added by other users of same level or higher lever (say Country-Manager)"

为了跟踪谁添加了条目,我将用户和组对象保存为 Lead 模型中的外键。

请建议任何策略或代码sn-p。

--

ps:我使用的是 Django 1.5

【问题讨论】:

    标签: python django permissions


    【解决方案1】:

    我在 mixins 的帮助下解决了这个问题。 (http://eflorenzano.com/blog/2008/05/17/exploring-mixins-django-model-inheritance/)

    因为我创建了一个 Hierarchy 类:

    class Hierarchy(models.Model):
        parent = models.ForeignKey('self',null=True,blank=True)
    
        def get_children(self):
            return self._default_manager.filter(parent=self)
    
        def get_descendants(self):
            descs = set(self.get_children())
            for node in list(descs):
                descs.update(node.get_descendants())
            return descs
    
        class Meta:
            abstract = True
    

    并在名为 GroupHirerarchy 的类中继承它:

    class GroupHierarchy(Hierarchy):
        group = models.ForeignKey(Group)
    
        def __unicode__(self):
            return self.group.name
    

    现在我可以使用 group_object.get_children() 和所有后代: group_object.get_descendants()

    现在使用这个我实现了模型的分层权限:

    glist = []
    groups = request.user.groups.all() 
    for group in groups:
            try:
                group_hierarchy = GroupHierarchy.objects.get(group = group)
                group_descendants = group_hierarchy.get_descendants()
                for group_descendant in group_descendants:
                    glist.append(Group.objects.get(name=group_descendant.group))
            except:
                pass
        obj =  Model.objects.filter(user_group__in = glist)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 2020-07-02
      相关资源
      最近更新 更多