我定义了以下模型
class Flight(models.Model):
...
class FlightUpdate(models.Model):
flight = models.ForeignKey('Flight', related_name='updates')
...
以及以下使用 REST Framework 扩展中的 NestedViewsetMixin
的 View 集
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'])
...
因此,要访问与 Flight
关联的 FlightUpdates
,URL 为 /flights/1/updates/
。
我想确保人们只有在有权更改航类
时才能创建FlightUpdates
FlightUpdate
关联的对象。
添加 FlightUpdate
时,我该如何执行额外检查?我试过在 View 集中添加这样的东西,但我不确定这是否是最好的方法。
if not request.user.has_perm('flights.change_flight', flight):
raise PermissionError()
注意:我正在使用 django-rules
来实现对象级权限。
最佳答案
我通过实现自定义权限类解决了这个问题。
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)
关于python - 检查 Django REST Framework 中相关对象的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879857/