Home > Software engineering >  Django nested viewsets on router
Django nested viewsets on router

Time:06-08

In my urls.py file in some app i have the following code:

from rest_framework import routers

from .viewsets import (JournalViewSet, StatisticViewSet, FuelLogViewSet,
                       MoveLogViewSet, RestLogViewSet, WinLogViewSet,
                       GreatfulLogViewSet)


router = routers.DefaultRouter()
router.register(r'journal', JournalViewSet)
router.register(r'journal/statistic', StatisticViewSet)
router.register(r'journal/fuel', FuelLogViewSet)
router.register(r'journal/move', MoveLogViewSet)
router.register(r'journal/rest', RestLogViewSet)
router.register(r'journal/win', WinLogViewSet)
router.register(r'journal/greatful', GreatfulLogViewSet)

urlpatterns = router.urls

All vievsets above are not something specific, and use only serializer_class and queryset. Swagger generate correct scheme, but DRF says, that i have no POST method allowed (in viesets i actually have) and when i try to open url like 127.0.0.1:8000/journal/win, drf return scheme for journal. When registers were not nested like router.register(r'move', MoveLogViewSet), I get all correct. I understand, that DRF maybe don't provide nested routs like I have. What should I do?

CodePudding user response:

I would strongly recommend you to read on the DefaultRouter from DRF.

It is because the second path is a lookup fields in DefaultRouter.

journal/fuel/ => {prefix}/{lookup}/[.format]

For your question:

from rest_framework import routers

from .viewsets import (JournalViewSet, StatisticViewSet, FuelLogViewSet,
                       MoveLogViewSet, RestLogViewSet, WinLogViewSet,
                       GreatfulLogViewSet)


router = routers.DefaultRouter()
# assessment_router = routers.DefaultRouter()
router.register(r'index', JournalViewSet) # Index 
router.register(r'statistic', StatisticViewSet)
router.register(r'fuel', FuelLogViewSet)
router.register(r'move', MoveLogViewSet)
router.register(r'rest', RestLogViewSet)
router.register(r'win', WinLogViewSet)
router.register(r'greatful', GreatfulLogViewSet)

# assessment_router.register(r'dashboard', SnippetViewSet)

urlpatterns = [
    path('journal/', include(router.urls)),
    # path('assessment/', include(assessment_router.urls)),
    # path('admin/', admin.site.urls),
    ]
  • Related