Django REST框架:限制用户对象的访问

时间:2016-01-18 17:49:39

标签: django permissions django-rest-framework

我正在尝试为书籍构建REST API:

/api/book
/api/book/{book_id}

用户应该只能访问他的书籍。我现在这样做的方法是使用用户名过滤结果,即Book.objects.all()。filter(owner = request.user)

views.py

class Book_List(APIView):

    permission_classes=(permissions.IsAuthenticated)

    def get(self, request, format=None):
        **books= Book.objects.all().filter(owner=request.user)**
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,   status=status.HTTP_400_BAD_REQUEST)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)    

#/book/{pk}
class Book_Detail(APIView):

    permission_classes = (permissions.IsAuthenticated)

    def get_object(self, pk, request):
        try:
            return Book.objects.get(pk=pk, owner=request.user)
        except Playlist.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        book = self.get_object(pk, request)
        serializer = BookSerializer(playlist, context={'request': request})
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        book= self.get_object(pk)
        serializer = BookSerializer(playlist, data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        book= self.get_object(pk)
        book.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

serializers.py

class BookSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = ('url', 'owner','title', 'created_date', 'shared_with', 'tracks')       

class UserSerializer(serializers.HyperlinkedModelSerializer):
    books = serializers.HyperlinkedRelatedField(many=True,view_name='playlist-detail', read_only=True)
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = User
        fields = ('url', 'username', 'owner', 'books') 

但这是正确的方法吗?

Django Rest Framework是否为此提供了任何内置解决方案?

解决方案是否属于权限?如果是,那么我们如何为用户创建的所有对象设置它(我理解为获取特定对象,我们可以像obj.user==request.user那样进行权限检查)。我是对的吗?

1 个答案:

答案 0 :(得分:4)

您可以使用ModelViewset,其中包含典型CRUD的所有逻辑:

boolean = !boolean