[Solved]-Extending custom router to default router across apps in Django Rest Framework

1πŸ‘

βœ…

The router registry is just a standard python list, so you can call YourRouter.registry.extend() directly on registy withouth the need to subclass the DefaultRouter, check the source of DRF here .
Since registry is a list, when you extend registry you add another python list on top of python list, which implies calling YourRouter.registry.extend(app_router.registry).
What worked for me, was importing routers from another apps (SimpleRouters) and adding them on top of default router registry.

#aplication_root/urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from app_3.urls import router as app_3_router


router = DefaultRouter()
router.registry.extend(app_3_router.registry)

urlpatterns = [

    path('api/', include(router.urls)),

]

If your are trying to add versioning to your app by adding the prefix, I suggest to take a look at versioning schema available in DRF – maybe it could fit your needs
DRF versioning

for example with URLPathVersioning enabled in your settings

REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning'
}

urlparttern list from snipped above would look like that

urlpatterns = [

    path('api/<version>/', include(router.urls)),
]

0πŸ‘

Have you tried leaving the default routes intact for SimpleRouter?

class App1Router(SimpleRouter):
    def __init__(self):
        super(SimpleRouter, self).__init__()
        self.routes.insert(0, Route(
            url = r'^{prefix}{trailing_slash}$',
            mapping = {
                'get': 'retrieve',
                'post': 'create',
                'patch': 'partial_update',
            },
            name = '{basename}-user',
            initkwargs = {}
        ))
πŸ‘€miigotu

0πŸ‘

I don’t see this anywhere in your code:
where the app1_router is a new SimpleRouter object

actually your import says otherwise
from app1.urls import router as app1_router

I would change the App1Router to extend either app1.urls.router or DefaultRouter.

πŸ‘€Xander YzWich

Leave a comment