基于 Django Rest Framework 中权限的不同查询集

different queryset based on permissions in Django Rest Framework

我已经看到了这个 link,但我没有找到任何与我的问题相关的信息来帮助解决它。

假设我们要创建一个博客,其中的帖子有两种状态:

  1. is_draft
  2. 已发布(published == !is_draft

因此,每个用户都应该看到所有 his/her 个帖子,无论是否为草稿。此外,其他用户应该可以看到其他用户发布的帖子。

我在 Django 中使用 viewsets,我知道我们应该根据当前用户权限使用不同的查询集,但我不知道如何。

models.py:

from django.db import models

# Create your models here.
from apps.authors.models import Author


class Post(models.Model):
    author = models.ForeignKey(
        Author,
        related_name="posts",
        on_delete=models.CASCADE,
    )

    title = models.TextField(
        null=True,
        blank=True,
    )

    content = models.TextField(
        null=True,
        blank=True,
    )

    is_draft = models.BooleanField(
        default=True
    )

views.py:

from django.shortcuts import render
from rest_framework import viewsets, permissions
# Create your views here.
from apps.posts.models import Post
from apps.posts.serializers import PostSerializer


class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

    def get_permissions(self):
        if self.action == "create":
            self.permission_classes = [permissions.IsAuthenticated]

        elif self.action == "list":
            pass #I don't know how can I change this part

        return super(PostViewSet, self).get_permissions()

serializers.py:

from rest_framework import serializers

from apps.posts.models import Post


class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

在您的视图集中像这样更改您的查询集。这样,只有您想要的帖子才会 accessed/permitted 被视图显示:

from django.shortcuts import render
from django.db.models import Q
from rest_framework import viewsets, permissions
# Create your views here.
from apps.posts.models import Post
from apps.posts.serializers import PostSerializer


class PostViewSet(viewsets.ModelViewSet):
    serializer_class = PostSerializer

    def get_permissions(self):
        if self.action == "create":
            self.permission_classes = [permissions.IsAuthenticated]

        return super(PostViewSet, self).get_permissions()

    def get_queryset(self, *args, **kwargs):
        current_user = self.request.user
        current_author = Author.objects.get(user=current_user) #assuming your author class has foreign key to user
        return Post.objects.filter(Q(author=current_author) | Q(is_draft=False))