是否可以根据查询字符串参数而不是URL资源名称或请求正文修改ViewSet的update()函数进行更新?
例如,我想要触发这样的东西:
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()函数。 任何帮助表示赞赏。
答案 0 :(得分:1)
假设你想使用相同的网址列表和检索实体的详细信息,区分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)