<p>出现此错误是因为URL <code>/person/</code>不用于<code>PUT</code>请求。<code>PUT</code>请求对应于viewsets<code>update</code>方法,<code>update</code>方法需要URL中的ID,例如<code>/person/10/</code>,以便检索要更新的<code>Person</code>对象。在</p>
<p>实际解决此问题的方法是扩展<a href="https://github.com/encode/django-rest-framework/blob/master/rest_framework/routers.py#L102" rel="nofollow noreferrer">^{<cd8>}</a>类,以便在列表端点上为<code>PUT</code>添加另一个操作,并自定义views <code>get_object</code>方法以从有效负载中检索ID。在</p>
<p>在<a href="https://github.com/encode/django-rest-framework/blob/master/rest_framework/routers.py#L102" rel="nofollow noreferrer">^{<cd11>}</a>类中,您将看到定义为:</p>
<pre><code>routes = [
# List route.
Route(
url=r'^{prefix}{trailing_slash}$',
mapping={
'get': 'list',
'post': 'create',
'put': 'update' # Add this entry to the mapping dictionary
},
name='{basename}-list',
detail=False,
initkwargs={'suffix': 'List'}
),
# Dynamically generated list routes. Generated using
# @action(detail=False) decorator on methods of the viewset.
DynamicRoute(
url=r'^{prefix}/{url_path}{trailing_slash}$',
name='{basename}-{url_name}',
detail=False,
initkwargs={}
),
# Detail route.
Route(
url=r'^{prefix}/{lookup}{trailing_slash}$',
mapping={
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
},
name='{basename}-detail',
detail=True,
initkwargs={'suffix': 'Instance'}
),
# Dynamically generated detail routes. Generated using
# @action(detail=True) decorator on methods of the viewset.
DynamicRoute(
url=r'^{prefix}/{lookup}/{url_path}{trailing_slash}$',
name='{basename}-{url_name}',
detail=True,
initkwargs={}
),
]
</code></pre>
<p>您需要将<code>{'put': 'update'}</code>添加到<code># List route.</code>部分,然后自定义视图集的<code>update</code>或{<cd10>}方法,以便它从负载中检索ID。我将提供一个自定义的<code>get_object</code>方法的示例,以支持此用例:</p>
^{pr2}$