我正在尝试在/path/to/API/widget/1/
的Django Rest Framework 3.6.3中检索模型实例,1是小部件的主键。它给了我:
retrieve()得到了一个意外的关键字参数'pk'
从跟踪中我认为我正在做一些事情导致dispatch
在实例化处理程序时抛出异常(来自views.py,source here)。当我检查来源时,我不明白我做错了什么。这是跟踪:
回溯:
File "/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/lib/python3.5/site-packages/rest_framework/viewsets.py" in view
86. return self.dispatch(request, *args, **kwargs)
File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
Exception Type: TypeError at /path/to/API/widget/1/
Exception Value: retrieve() got an unexpected keyword argument 'pk'
以下是ViewSet
:
def retrieve(self, request, some_lookup_field=None):
instance = self.get_object(pk) # handle multi-tenant access control
if not instance:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = self.get_serializer(instance) # from the class's `serializer_cass` attribute
return Response(serializer.data)
答案 0 :(得分:0)
正如您在堆栈跟踪中看到的那样,错误是:
retrieve()
收到了意外的关键字参数'pk'
。
仔细查看retrieve()
函数:
def retrieve(self, request, some_lookup_field=None):
# ____________________________^
instance = self.get_object(pk) # handle multi-tenant access control
# _________________________^
...
您将some_lookup_field
作为参数而非pk
,您在self.get_object(pk)
中使用了以下内容。尝试将some_lookup_field
重命名为pk
。