检查 Django REST Framework 中相关对象的权限

Kie*_*ran 5 python django permissions django-rest-framework

我定义了以下模型

class Flight(models.Model):
    ...

class FlightUpdate(models.Model):
    flight = models.ForeignKey('Flight', related_name='updates')
    ...
Run Code Online (Sandbox Code Playgroud)

NestedViewsetMixin以及使用REST Framework 扩展中的以下视图集

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'])
        ...
Run Code Online (Sandbox Code Playgroud)

因此,要访问FlightUpdates与 a 关联的Flight,URL 为/flights/1/updates/

我想确保人们只有在有权更改与之关联的对象时才能创建。 FlightUpdatesFlightFlightUpdate

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

if not request.user.has_perm('flights.change_flight', flight):
    raise PermissionError()
Run Code Online (Sandbox Code Playgroud)

注意:我用于django-rules对象级权限实现。

Kie*_*ran 4

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

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)
Run Code Online (Sandbox Code Playgroud)