是否可以修改ViewSet的update()函数以基于查询字符串参数而不是URL资源名称或请求正文进行更新?

例如,我想触发类似这样的事情:

payload = {'field' : '2'}
r = requests.put("http://127.0.0.1:9876/job-defs?job-def-id=2", data=payload)


并在job-def-id = 2时更新我的​​字段。

我到目前为止所拥有的是:

class JobDefinitionsViewSet(mixins.ListModelMixin,
                        mixins.CreateModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        viewsets.GenericViewSet):

    serializer_class = JobDefinitionsSerializer

    def update(self, request, pk=None):
        job_def_id = self.request.query_params.get('job-def-id', None)
        super(JobDefinitionsViewSet, self).update(self, request, pk=job_def_id)

    ...
    # other unrelated code
    ...


我不太确定如何继续。
我想尽可能多地重用mixins.UpdateModelMixin中的update()函数。
任何帮助表示赞赏。

最佳答案

假设您要使用相同的url进行列出和检索实体的详细信息,并区分url参数job-def-id的存在,这是一个疯狂的主意:

class JobDefinitionsAllInOneView(mixins.UpdateModelMixin,
                                 mixins.DestroyModelMixin,
                                 mixins.ListModelMixin,
                                 mixins.CreateModelMixin,
                                 generics.GenericAPIView):

    queryset = JobDefinitions.objects.all()
    serializer_class = JobDefinitionsSerializer

    def get_object(self):
        job_def_id = self.request.query_params.get('job-def-id', None)
        if job_def_id is not None:
            self.kwargs['pk'] = job_def_id
        return super(JobDefinitionsAllInOneView, self).get_object()

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        job_def_id = self.request.query_params.get('job-def-id', None)
        if job_def_id is not None:
            # return the details
            return self.retrieve(request, *args, **kwargs)
        else:
            # return a list
            return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.partial_update(self, request, *args, **kwargs)
    def delete(self, request, *args, **kwargs):
        return self.destroy(self, request, *args, **kwargs)


我还没有尝试过。我看了get_object的源代码here和mixins的here

10-02 09:12