gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:11:32 24 4
gpt4 key购买 nike

我见过这个link ,但我没有找到任何与我的问题相关的内容来帮助它解决。
想象一下,我们必须创建一个博客,其中的帖子有两种状态:

  • is_draft
  • 已发布 ( published == !is_draft )

  • 因此,每个用户都应该看到他/她的所有帖子,无论是否是草稿。此外,其他用户应该可以看到其他用户发布的帖子。
    我正在使用 viewsets在 django 中,我知道我们应该根据当前用户权限使用不同的查询集,但我不知道如何。
    模型.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
    )
    View .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()

    序列化程序.py:
    from rest_framework import serializers

    from apps.posts.models import Post


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

    最佳答案

    在您的 View 集中像这样更改您的查询集。这样, 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))

    关于python - 基于 Django Rest Framework 中权限的不同查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65156787/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com