Search code examples
djangodjango-rest-frameworkuser-permissionsdatabase-permissions

Django REST Framework: restrict data records access to the users created them


I'm trying to figure out, what is the best way to manage model access permissions with Django.

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.

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?


Solution

  • 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)
    

    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)
    

    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.