Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drf-nested-routers RuntimeError('parent registered resource not found')

I am attempting to utilize the package drf-nested-routers to created nested routes within my API.

I've attempted to follow alongside the documentation (https://github.com/alanjds/drf-nested-routers) as well as read through multiple Stackoverflow threads in hopes to figure out this issue.

I would like to create a single NestedSimpleRouter. Here is what I have so far inside of my routers.py file:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework_nested import routers
from api_v1.viewsets import DeviceViewSet, BreadcrumbViewSet

router = DefaultRouter()
router.register(r'devices', DeviceViewSet, base_name='devices')

device_breadcrumbs_router = routers.NestedSimpleRouter(router, r'breadcrumbs', lookup='breadcrumb')
device_breadcrumbs_router.register(r'breadcrumbs', BreadcrumbViewSet, base_name='breadcrumbs')

api_url_patterns = [
    path('', include(router.urls)),
    path('', include(device_breadcrumbs_router.urls)),
]

I then include the api_url_patterns in my urls.py file:

from django.contrib import admin
from django.urls import path, include
from .routers import api_url_patterns

urlpatterns = [
    path('api/v1/', include(api_url_patterns)),
    path('admin/', admin.site.urls),
]

And here are my Viewsets:

class DeviceViewSet(viewsets.ModelViewSet):
    serializer_class = DeviceSerializer

    def get_queryset(self):
        return Device.objects.all()


class BreadcrumbViewSet(viewsets.ModelViewSet):
    serializer_class = BreadcrumbSerializer

    def get_queryset(self):
        device_id = self.kwargs.get('device', None)
        return Breadcrumb.objects.filter(device_id=device_id)

The hope is to have a URL pattern that looks like /api/v1/devices/<device_id>/breadcrumbs/. Unfortunately, the code I have displayed above is resulting in the error RuntimeError('parent registered resource not found')

I can't seem to figure out why this error is occurring with that I have provided. Any help would be much appreciated.

like image 728
Bonteq Avatar asked Mar 16 '19 23:03

Bonteq


1 Answers

Change this line

device_breadcrumbs_router = routers.NestedSimpleRouter(router, r'breadcrumbs', lookup='breadcrumb')

to

device_breadcrumbs_router = routers.NestedSimpleRouter(router, r'devices', lookup='breadcrumb')

From DRF nested router's docs

router = routers.SimpleRouter()
router.register(r'domains', DomainViewSet)

domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
domains_router.register(r'nameservers', NameserverViewSet, base_name='domain-nameservers')

Notice how the r"domains" match. The error is trying to say that it couldn't find a url to add the nested resources to. It was looking for a /breadcrumbs but that didn't exist.

like image 157
Bufke Avatar answered Oct 24 '22 09:10

Bufke