问题描述
我试图弄清楚,使用Django管理模型访问权限的最佳方法是什么。
I'm trying to figure out, what is the best way to manage model access permissions with Django.
我有一张属于用户的项目表创建了它们。所有项目都通过RESTful API进行管理。使用此API时,我想限制对给定用户创建的项目的访问。
I have a table of items which belong to the users created them. All the items a managed via a RESTful API. When using this API I want to limit access to the items created by a given user.
我是否必须创建多个表,还是可以仅通过创建几个表来实现?一张桌子?
如果必须使用多个表,如何将API请求与特定表相关联?
Do I have to create several tables or is it possible to achieve the same with just one table?If I have to use multiple tables, how do I correlate API requests with a particular table?
推荐答案
好,我找到了一种通过API和admin进行操作的方法。
Ok, I found a way to do it via both API and admin. This basically resembles Rob's idea.
首先,每次我通过管理面板创建新用户时,都需要将用户添加到我的商品中:
First of all, every time I create a new user via admin panel, I need to append a user to my items:
class MyAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if getattr(obj, 'user', None) is None:
obj.user = request.user
obj.save()
admin.site.register(MyItem, MyAdmin)
然后在访问模型时,我只是按用户过滤(这是django.contrib.auth.models.User):
Then when accessing my model, I just filter by user (which is btw a foreign key to django.contrib.auth.models.User):
MyItem.objects.filter(user=request.user)
最后要使其与Django REST Framework一起使用,我需要向我的自定义ModelViewSet中添加几个方法: / p>
Finally to make it work with Django REST Framework, I need to add a couple of methods to My custom ModelViewSet:
class MyItemViewSet(viewsets.ModelViewSet):
model = MyItem
serializer_class = MyItemSerializer
def get_queryset(self):
return MyItem.objects.filter(user=self.request.user)
def pre_save(self, obj):
obj.user = self.request.user
我使用文档和(很多)试验和错误来弄清楚这一点。
I've used documentation and (lots) trial and error to figure this out.
这篇关于Django REST Framework:将数据记录访问权限限制为创建它们的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!