drf ModelViewSet之匹配路由参数

urls.py

    url(r'employees/(?P\d+)/detail/', EmployeesViewSet.as_view({'get': 'retrieve'})),

views.py

class EmployeesViewSet(DestroyModelMixin, CreateModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
    serializer_class = EmployeesSerializer
    # queryset = models.Employees.objects.filter(tags=0).all().order_by("-create_time")
    permission_classes = [IsAuthenticated]
    ordering_fields = ('name', 'department', 'add_people')
    lookup_url_kwarg = 'employee_id'
    filterset_class = EmployeesManagerFilter
    # filter_backends = [filters.DjangoFilterBackend]
    # search_fields = ['$name', '$email']

    def get_queryset(self, *args, **kwargs):
        # department_id = self.request.query_params.get("department_id", "")
        #
        # if department_id:
        #     return models.Department.objects.get(id=department_id).linkdepartments.filter(tags=0).all()

        return models.Employees.objects.filter(tags=0).order_by("-create_time")

    def get_serializer_class(self):
        # print(self.action)
        if self.action == 'add':
            return EmployeesCreateSerializer
        elif self.action == 'partial_update':
            return EmployeesUpdateSerializer
        elif self.action in ['add_invite', 'invite']:
            return EmployeesInviteSerializer

        return EmployeesSerializer

其中:

    views.py 中添加 lookup_url_kwarg = 'employee_id' 自动获取路由中的参数 注意lookup_url_kwarg后面的参数名需要和路有中的无名分组的参数名一致才能
获取到值。

你可能感兴趣的:(drf ModelViewSet之匹配路由参数)