django admin 中基于用户的模型实例过滤 [英] User-based model instances filtering in django admin
问题描述
我正在使用 django 的管理员来让用户管理特定模型的模型实例.每个用户应该只能管理他的模型实例.(除了应该管理所有的管理员).
I'm using django's admin to let users manage model instances of a specific model. Each user should be able to manage only his model instances. (except for administrators which should manage all).
如何过滤管理员更改列表视图中的对象?
How do I filter the objects in the admin's changelist view?
想法:
- 我想最优雅的方法是使用 对象级权限.有人知道这个的实现吗?
- 是否可以使用 ModelAdmin.changelist_view 覆盖管理员的视图?
- list_select_related 跟它有关系吗?
- I guess the most elegant approach would be to use Object-level permissions. Anyone aware of an implementation of this?
- Is it possible to do by overriding the admin's view using ModelAdmin.changelist_view?
- Does list_select_related have anything to do with it?
推荐答案
您可以覆盖管理员的 queryset
方法以仅显示用户的项目:
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)
此外,您还应该注意 has_change_permission
和 has_delete_permission
方法,例如:
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)
has_change_permission
也一样!list_select_related
仅在获取管理员的查询集以立即从关系中获取相关数据时使用,而不是在需要时使用!
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!
如果您的主要目标只是限制用户无法使用其他对象,则上述方法将起作用,如果它变得越来越复杂并且您不能简单地从 ONE 属性(例如用户)中判断权限,则查看 django 的行级权限提案!
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!
这篇关于django admin 中基于用户的模型实例过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!