Django Rest Framework中基于权限的不同查询集 [英] different queryset based on permissions in Django Rest Framework
问题描述
我已经看到了这个链接,但是我没有找不到与我的问题有关的任何东西来帮助其解决.
I have seen this link, but I didn't find anything related to my question helping it being resolved.
假设我们必须创建一个博客,其中的帖子具有两种状态:
Imagine we have to create a blog, in which posts have two status:
- is_draft
- 已发布(
已发布==!is_draft
)
因此,每个用户都应该看到他/她的所有帖子,无论它是否是草稿.另外,其他用户"应查看其余用户的已发布帖子.
So, each user should see all of his/her posts, whether it is draft or not. In addition, Other users should see the published posts of rest of the users.
我正在django中使用 viewsets
,我知道我们应该基于当前用户权限使用不同的查询集,但是我不知道如何.
I am using viewsets
in django and I know that we should have different queryset based on the current user permissions but I don't know how.
models.py:
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:
serializers.py:
from rest_framework import serializers
from apps.posts.models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
推荐答案
在视图集中像这样更改查询集.这样,视图将仅访问/允许您所需的帖子:
Change your queryset like this in your viewset. That way, only your desired posts will be accessed/permitted by the view:
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))
这篇关于Django Rest Framework中基于权限的不同查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!