Django Rest Framework with multiple Viewsets and Routers for the same object

后端 未结 1 1409
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 04:12

I am having trouble defining different view sets for the same object using Django Rest Framework. Following is a minimal example to reproduce the issue, based on DRF Quickst

相关标签:
1条回答
  • 2020-12-19 04:23

    Short answer: You have to add the basename parameter to your route to users-minimal:

    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    router.register(r'users-minimal', UserMinimalViewSet, basename='usersminimal')
    

    Normally DRF genereates a basename automatically from your queryset. This is explained in the DRF routers docs, search for basename.

    Your two Viewsets use the same queryset so the have initially the same basename. That leads to the problems which you have seen, that the later registered ViewSet will overwrite the routes from the former registered ViewSet. You can see this in action when you change the order of the router.register in your example.

    You can see the base names of your routes when you test the code directly in the shell:

    from rest_framework import routers
    from tutorial.quickstart import views
    
    router = routers.DefaultRouter()
    router.register(r'users', views.UserViewSet)
    router.register(r'users-minimal', views.UserMinimalViewSet)
    
    
    > routers.urls
    [<RegexURLPattern user-list ^minimal/$>,
    <RegexURLPattern user-list ^minimal\.(?P<format>[a-z0-9]+)/?$>,
    <RegexURLPattern user-detail ^minimal/(?P<pk>[^/.]+)/$>,
    <RegexURLPattern user-detail ^minimal/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$>,
    <RegexURLPattern user-list ^users/$>,
    <RegexURLPattern user-list ^users\.(?P<format>[a-z0-9]+)/?$>,
    <RegexURLPattern user-detail ^users/(?P<pk>[^/.]+)/$>,
    <RegexURLPattern user-detail ^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$>,
    <RegexURLPattern api-root ^$>,
    <RegexURLPattern api-root ^\.(?P<format>[a-z0-9]+)/?$>]
    
    0 讨论(0)
提交回复
热议问题