User-based model instances filtering in django admin

血红的双手。 提交于 2019-11-30 07:45:53
Bernhard Vallant

You can override the admin's queryset-method to just display an user's items:

    def queryset(self, request):
        user = getattr(request, 'user', None)
        qs = super(MyAdmin, self).queryset(request)
        if user.is_superuser:
            return qs
        return qs.filter(user=user)

Besides that you should also take care about the has_change_permission and has_delete_permission-methods, eg like:

    def has_delete_permission(self, request, obj=None):   
        if not request.user == obj.user and not request.user.is_superuser:
            return False
        return super(MyAdmin, self).has_delete_permission(request, obj)

Same for has_change_permission! list_select_related is only used when getting the admin's queryset to get also related data out of relations immediately, not when it is need!

If your main goal is only to restrict a user to be not able to work with other's objects the above approch will work, if it's getting more complicated and you can't tell a permissions simply from ONE attribute, like user, have a look into django's proposal's for row level permissions!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!