Python 检查Django REST框架中相关对象的权限

Python 检查Django REST框架中相关对象的权限,python,django,permissions,django-rest-framework,Python,Django,Permissions,Django Rest Framework,我定义了以下模型 class Flight(models.Model): ... class FlightUpdate(models.Model): flight = models.ForeignKey('Flight', related_name='updates') ... 下面的视图集使用REST框架扩展中的NestedViewsetMixin class FlightUpdateViewSet(mixins.ListModelMixin,

我定义了以下模型

class Flight(models.Model):
    ...

class FlightUpdate(models.Model):
    flight = models.ForeignKey('Flight', related_name='updates')
    ...
下面的视图集使用REST框架扩展中的
NestedViewsetMixin

class FlightUpdateViewSet(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      NestedViewSetMixin,
                      viewsets.GenericViewSet):
    """
    API Endpoint for Flight Updates
    """
    queryset = FlightUpdate.objects.all()
    serializer_class = FlightUpdateSerializer

    def create(self, request, *args, **kwargs):
        flight = Flight.objects.get(pk=self.get_parents_query_dict()['flight'])
        ...
因此,要访问与
航班相关的
航班更新
,URL为
/flights/1/updates/

我想确保人们只有在拥有更改
FlightUpdate
关联的
FlightUpdate
对象的权限时才能创建
FlightUpdates

添加
FlightUpdate
时,如何执行额外检查?我曾尝试在视图集中添加类似的内容,但我不确定这是否是最好的方法

if not request.user.has_perm('flights.change_flight', flight):
    raise PermissionError()

注意:我正在使用
django规则
实现对象级权限。

我通过实现自定义权限类解决了这个问题

from django.core.exceptions import ObjectDoesNotExist

from rest_framework.permissions import BasePermission, SAFE_METHODS

from .models import Flight


class FlightPermission(BasePermission):

    def has_permission(self, request, view):
        if request.method in SAFE_METHODS:
            return True

        try:
            flight = Flight.objects.get(pk=view.kwargs['parent_lookup_flight'])
        except ObjectDoesNotExist:
            return False

        return request.user.has_perm('flights.change_flight', flight)

谢谢你!经历了同样的问题。我已经看过你的答案了。但是需要几个小时才能赶上你找到了解决办法!