0

我希望创建一个 API,允许用户访问/更新仅由他们上传的书籍的详细信息。用户不应有权访问/更新由其他人创建的图书。

这是我的models.py

from django.contrib.auth.models import User

class Project(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=200)


class Book(models.Model):
    project = models.ForeignKey(Project,on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    total_pages = models.IntegerField()

这是我的serializers.py

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = "__all__"

这是我的views.py

class BookDetails(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = BookSerializer
    queryset = Book.objects.all()

如何修改views.py用户只能访问/更新他创建的书籍?

4

1 回答 1

0

在您的视图中使用get_queryset方法并根据经过身份验证的用户过滤查询集:

class BookDetails(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = BookSerializer

    def get_queryset(self):
        user = self.request.user
        return Book.objects.filter(project__user=user)
于 2018-10-24T09:56:06.790 回答