如何在django rest框架中为多对多字段定义“isowner”自定义权限?

bejyjqdl  于 2021-09-08  发布在  Java
关注(0)|答案(0)|浏览(180)

我对django非常陌生,尤其是django rest框架。所以在我的这个项目练习中。我想拥有一个对象级权限,一个isowner自定义权限,其中只有作者可以修改它。
我的模型如下所示:


# imports

class Book(models.Model):

    title = models.CharField(max_length=100)
    description = models.CharField(max_length=400)
    publisher = models.CharField(max_length=400)
    release_date = models.DateField()
    authors = models.ManyToManyField('Author', related_name='authors', blank=True)

    def __str__(self):
        return self.title

class Author(models.Model):

    user= models.ForeignKey(
        User, on_delete=models.CASCADE, default=1)
    biography  = models.TextField()
    date_of_birth = models.DateField()
    #books = models.ManyToManyField('Book', related_name='authors', blank=True)

    def __str__(self):
        return self.user.username

这是序列化程序


# imports here

class BookSerializer(serializers.ModelSerializer):

    class Meta:
        ordering = ['-id']
        model = Book
        fields = ("id", "title", "description", "publisher", "release_date", "authors")
        extra_kwargs = {'authors': {'required': False}}

class AuthorSerializer(serializers.ModelSerializer):
    books = BookSerializer(many=True, read_only=True)
    class Meta:
        ordering = ['-id']
        model = Author
        fields = ("id", "user", "biography", "date_of_birth", "books")
        extra_kwargs = {'books': {'required': False}}

views.py是这样的:


# imports here

class IsAnAuthor(BasePermission):
    message = 'Editing book is restricted to the authors only.'

    def has_object_permission(self, request, view, obj):

        if request.method in SAFE_METHODS:
            return True
        # I need to filter who can only edit book in this part but
        # obj.authors when print is none
        return obj.authors == request.user

class BookViewSet(viewsets.ModelViewSet):
    """
    List all workkers, or create a new worker.
    """
    permission_classes=[IsAnAuthor]
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['release_date']

class AuthorViewSet(viewsets.ModelViewSet):
    """
    List all workers, or create a new worker.
    """
    #permission_classes=[IsAuthenticatedOrReadOnly]
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

我试图实现的是与作者和书籍的多对多关系,并对其实现自定义所有者权限。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题