django 选定字段仅部分用户

50pmv0ei  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(116)

我有一个任务模型,其中一个字段是状态。
如何使NEW和COMPLITED状态仅由任务的作者选择,而这些状态对执行者不可用?
models.py

class Tasks(models.Model):
    STATUS_CHOICE = (
        ('new', 'new'),
        ('in progress', 'in progress'),
        ('on finish', 'on finish'),
        ('completed', 'completed')
    )

    title = models.CharField(max_length=255)
    text = models.TextField()
    status = models.CharField(max_length=255, choices=STATUS_CHOICE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    performers = models.ManyToManyField(User, blank=True, related_name='performers')
    date_create = models.DateField(default=now)
    date_update = models.DateField(blank=True, null=True)

serializers.py

class TasksSerializer(ModelSerializer):
    author = SlugRelatedField(read_only=True, slug_field='username')
    performers = SlugRelatedField(many=True, read_only=True, slug_field='username')
   
    class Meta:
        model = Tasks
        fields = '__all__'

views.py

class TasksViewSet(ModelViewSet):
    permission_classes = [IsAuthenticated, IsPerformers]
    queryset = Tasks.objects.all()
                .select_related('author')
                .prefetch_related('performers')
    serializer_class = TasksSerializer

    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['status']
    search_fields = ['title', 'text']
    ordering_fields = ['date_create', 'date_update', 'author', 'status']

你能告诉我如何实现这一点吗?

njthzxwz

njthzxwz1#

我认为可能有效的是在你的ModelViewSet中检查这个:

from rest_framework.exceptions import PermissionDenied

class TasksViewSet(ModelViewSet):
    # ...

    def update(self, request, *args, **kwargs):
        task = self.get_object()
        if task.status != request.data.get('status') and request.user != task.author:
            raise PermissionDenied('You are not allowed to change the status of this task')
        return super().update(request, *args, **kwargs)

self.get_object()将获取数据库中对象的当前状态。然后我们将其与API调用中接收到的状态进行比较,如果不匹配,则检查请求是否。user == author

相关问题