我看到了这个link,但我没有发现任何与我的问题相关的东西有助于它的解决
假设我们必须创建一个博客,其中的帖子有两种状态:
published == !is_draft
)因此,每个用户都应该看到他/她的所有帖子,无论它是否是草稿。另外,其他用户应该看到其他用户发布的帖子
我在django中使用viewsets
,我知道我们应该根据当前用户权限使用不同的queryset,但我不知道如何使用
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__'
在视图集中像这样更改查询集。这样,视图将只访问/允许您所需的帖子:
相关问题 更多 >
编程相关推荐