Django REST Framework combining routers from different apps

前端 未结 6 1860
面向向阳花
面向向阳花 2020-12-12 14:33

I have a project that spans multiple apps:

./project/app1
./project/app2
./project/...

Each app has a router for Django REST Framework to i

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 14:49

    I ended up creating a single URLs file that contains all the routes I want at urls_api_v1.py:

    router = DefaultRouter()
    router.register(r'app1/foos', FooViewSet, base_name='foo')
    router.register(r'app2/bars', BarViewSet, base_name='bar')
    router.register(r'app2/bazs', BazViewSet, base_name='baz')
    

    As a side effect, this allowed me to get rid of all the individual urls.py files in each app, which you would normally want but in this case the entire collection of apps needs a unified URL structure and so removal is more sensible.

    I then reference it from urls.py:

    import api_v1
    urlpatterns = patterns('',
        ...,
        url(r'^api/v1/', include(api_v1, namespace='api-v1')),
    )
    

    Now if I ever want to change routes for v2, I can just include a v2 URLs file as well and eventually deprecate the v1 file.

提交回复
热议问题