如何保证用户只能access/update自己创建的数据

How to ensure that users can only access/update data created by them

我希望创建一个 API 允许用户 access/update 仅由他们上传的图书的详细信息。用户不应该 access/update 其他人创建的图书的权限。

这是我的 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 使用户只能 access/update 自己创建的图书?

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

class BookDetails(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = BookSerializer

    def get_queryset(self):
        user = self.request.user
        return Book.objects.filter(project__user=user)