如何在rest_framework中创建嵌套路由器urs?

时间:2018-09-22 08:40:00

标签: python django django-rest-framework

我已经使用NestedSimpleRouter创建了一个网址。我创建的网址是:

http://localhost:8000/api/category/1/subcategory/

然后在类别ID的网址1上方,我的问题是 我想创建这样的网址

http://localhost:8000/api/category/1/subcategory/1/interest

1是subcategory_id

所以我如何为此URL定义嵌套URL。我的urls.py如下:

urls.py:

from django.urls import path,include
from rest_framework_nested import routers

from campaignapp import views

router = routers.DefaultRouter()
router.register('campaign',views.CampaignViewSet)
router.register('interestbundle',views.InterestBundleViewSet)
router.register('category',views.CategoryViewSet,'category')

category_router = routers.NestedSimpleRouter(router, r'category', lookup='category')
category_router.register(r'subcategory', views.SubcategoryViewSet, base_name='category-subcategory')




urlpatterns = [
    path('',include(router.urls)),
    path('',include(category_router.urls))
]

1 个答案:

答案 0 :(得分:0)

您可以使用actionlist_route or detail_route(older version of django rest framework)装饰器向视图集中添加其他操作。此装饰器适用于从ViewSetMixin类继承的所有ViewSet。