我定义了以下模型
class Flight(models.Model):
...
class FlightUpdate(models.Model):
flight = models.ForeignKey('Flight', related_name='updates')
...
以及使用以下视图集NestedViewsetMixin
在 REST 框架扩展中
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'])
...
因此,要访问FlightUpdates
与一个相关联Flight
,网址是/flights/1/updates/
.
我想确保人们只能create FlightUpdates
如果他们有权限change the Flight
对象与FlightUpdate
已关联的。
添加时我将如何执行额外检查FlightUpdate
?我尝试在视图集中添加类似的内容,但我不确定这是否是最好的方法。
if not request.user.has_perm('flights.change_flight', flight):
raise PermissionError()
注意:我正在使用django-rules
用于对象级别的权限实现。