Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

routing one rest resource as a child of a second rest resource

Using Django 1.6 and Rest Framework 2.

I have a uri

 /rest/parent_resource/951

below that I want to present a second resource as a child of that resource, with create, list, get and delete methods

 /rest/parent_resource/951/child_resource

I am new and still learning, I tried this url config:

 router.register(r'parent_resource', diliMarketplace.MarketPlaceProposalViewSet_Internal)

then registering the router I added:

 url(r'^rest/parent_resource/(?P<parent_resource_pk>[0-9]+)/child_resource/$', ChildViewset.as_view())
url(r'^rest/', include(router.urls)),

and the following viewset:

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

The error I am getting (in the hope I am heading in the right direction):

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'

I think the URL Router generated REGEX is being too agressive, and is routing to my parent_resource viewset and looking for an @Action or @Link...


So what is happening is the URL routing is routing this to the parnet_resource trying to find a child_resource @action. so the question is how to route to a child resource viewset without routing through the parent_resource viewset @action methods.

like image 888
akaphenom Avatar asked Jan 14 '14 15:01

akaphenom


1 Answers

Really digging into the source and re-reading the tutorial, left me with a better understanding of the URL config

url(r'^rest/parent_resource/(?P<parent_resource_pk>[0-9]+)/child_resource/$', ChildViewset.as_view({
        'get': 'list',
        'post': 'create'
    }))

I needed too list the methods in the as_view method.

like image 188
akaphenom Avatar answered Oct 12 '22 02:10

akaphenom