使用Django 1.6和Rest Framework 2.
我有一个uri
/rest/parent_resource/951
下面我想用第二个资源作为该资源的子项,使用create,list,get和delete方法
/rest/parent_resource/951/child_resource
我是新手,还在学习,我试过这个url配置:
router.register(r'parent_resource', diliMarketplace.MarketPlaceProposalViewSet_Internal)
然后注册我添加的路由器:
url(r'^rest/parent_resource/(?P<parent_resource_pk>[0-9]+)/child_resource/$', ChildViewset.as_view())
url(r'^rest/', include(router.urls)),
和以下视图集:
class ChildViewset(viewsets.ModelViewSet):
paginate_by = 100
queryset = diliModels\
.ChildModel\
.objects\
.exclude(status=0)\
.prefetch_related('parent_model')\
.all()
serializer_class = diliSerializers.MarketPlaceProposalBidSerializer
permission_classes = (MyAuth.MyAuthIsAuthenticated,)
def get_queryset(self):
queryset = None
parent_pk = self.kwargs['parent_resource_pk']
if proposal_pk is not None:
request = self.get_serializer_context()['request']
authenticatedUserId = request.user.user_id
queryset = self.queryset.filter(parent_model__id = parent_pk) & \
self.queryset.filter(parent_model__user__user_id = authenticatedUserId)
return queryset
我得到的错误(希望我朝着正确的方向前进):
Internal Server Error: /rest/parent_resource/951/child_resource/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\rest_framework\viewsets.py", line 69, in view
for method, action in actions.items():
AttributeError: 'NoneType' object has no attribute 'items'
我认为URL路由器生成的REGEX过于激进,并且路由到我的parent_resource视图集并寻找@Action或@Link ......
所以发生的事情是URL路由将此路由到parnet_resource,试图找到child_resource @action。所以问题是如何路由到子资源视图集而不通过parent_resource视图集@action方法进行路由。
答案 0 :(得分:5)
真正深入挖掘源代码并重新阅读教程,让我更好地理解了URL配置
url(r'^rest/parent_resource/(?P<parent_resource_pk>[0-9]+)/child_resource/$', ChildViewset.as_view({
'get': 'list',
'post': 'create'
}))
我也需要列出as_view方法中的方法。