DRF 中的 ModelViewSets 确实很有帮助,但我正在尝试扩展其中一个,以便能够在 GET 请求中返回对象列表,并在 POST 请求中处理列表。到目前为止,我似乎需要使用 @list_route
装饰器来添加此功能。
我已经使用它在其他 View 集中添加自定义路由,但是这是我第一次尝试添加接受多个方法的路由。这是我到目前为止所拥有的:
class PickViewset(viewsets.ModelViewSet):
queryset = Pick.objects.all()
serializer_class = PickSerializer
def get_queryset(self):
#gets the correct queryset
@list_route(methods=['get', 'post'])
def update_picks(self, request, league, week, format = None):
if request.method == 'POST':
#process/save objects here
else:
#otherwise return the requested list
我认为这可行,并且我的问题在 urls.py
中 - 这是那里的相关内容:
#bind the pick methods explicitly
update_picks = PickViewset.as_view({'get': 'update_picks'})
url(r'^api/picks/(?P<league>[\w ]+)/(?P<week>[0-9]+)/$', update_picks, name='update_picks')
这对于 GET 请求来说效果很好,如果我将 update_picks
定义更改为
update_picks = PickViewset.as_view({'get': 'update_picks'})
然后我可以从 View 集中进入 POST 代码。我需要做什么才能将 GET 和 POST 请求路由到 update_picks 操作,然后可以通过请求方法区分它们?
我尝试向 as_view() 添加 , {'post': 'update_picks'}
,但这不起作用。
我也尝试添加
get_picks = PickViewset.as_view({'get': 'update_picks'})
使用新的 URL 模式
url(r'^api/picks/(?P<league>[\w ]+)/(?P<week>[0-9]+)/$', get_picks, name='get_picks'),
但这也不起作用。
我考虑过使用相同的 URL 建立单独的 list_routes
,但这似乎不受支持,尽管我可能错过了文档中的某些内容。
感谢您的帮助!
最佳答案
ViewSet 的 actions
参数是一个字典,所有方法都在该字典中:
get_picks = PickViewset.as_view({
'get': 'update_picks',
'post': 'update_picks',
})
关于python - 通过 Django REST Framework list_route 使用单个 URL 进行 GET 和 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423218/