我有一个用DRF编写的视图集:
class MyViewSet(ModelViewSet):
serializer_class = MySerializer
queryset = models.MyClass.objects.all()
def get_serializer_class(self):
permission = self.request.user.permission
if permission=='owner' or permission=='admin':
return self.serializer_class
else:
return OtherSerializer
def perform_create(self, serializer):
permission = self.request.user.permission
if permission=='owner' or permission=='admin':
serializer.save()
else:
employee = models.Employee.objects.get(user=self.request.user)
serializer.save(employee=employee)
这里,我在get_serializer_class和perform_create中使用了以下语句,看起来像是重复的代码:
permission = self.request.user.permission
if permission=='owner' or permission=='admin':
有没有办法写一次,然后用它作为permission_class?
1条答案
按热度按时间carvr3hs1#
创建自定义权限类www.example.comhttps://www.django-rest-framework.org/api-guide/permissions/#custom-permissions
在www.example.com中Views.py