您好,我已经设置了一个包含 REST api 的 Django 项目,到目前为止,这是项目结构:
django
│
├───apps
│ ├───store
│ | admin.py
│ | apps.py
│ | models.py
│ | serializers.py
│ | tests.py
│ | urls.py
│ | views.py
│ | viewsets.py
│ | __init__.py
│ ├───accounts
│ admin.py
│ apps.py
│ models.py
│ serializers.py
│ tests.py
│ urls.py
│ views.py
│ viewsets.py
│ __init__.py
├───main
asgi.py
router.py
settings.py
urls.py
wsgi.py
__init__.py
在 main/urls.py 中,我有类似的内容(通过包含 routers.py 来设置 API url 端点):
from django.contrib import admin
from django.urls import path, include
from .router import router
urlpatterns = [
# Default urls
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
path('', include('apps.store.urls')),
]
在 main/routers.py 中,我正在注册所有项目的所有 View 集:
from rest_framework.routers import DefaultRouter
from apps.store.viewsets import ItemViewSet, PurchaseViewSet, ReceiptViewSet
from apps.accounts.viewsets import ProfileViewSet, TransactionViewSet
router = DefaultRouter()
router.register('items', ItemViewSet)
router.register('purchases', PurchaseViewSet)
router.register('receipts', ReceiptViewSet)
router.register('profiles', ProfileViewSet)
router.register('transactions', TransactionViewSet)
一切正常,但我的问题是,在这个 routers.py 中,我必须注册整个项目的所有 ViewSet,我猜这对模块化没有帮助,并且会使这个文件变得又大又困惑。
问题: 是否可以为每个应用程序创建一个 routers.py,然后以某种方式将它们导入并合并到 main/routers.py 中,或者是否有其他方法可以在每个应用程序中为每个应用程序注册 View 集?或者还有其他推荐的方法吗?
我希望问题很清楚,非常感谢!
最佳答案
我刚刚发现最好的方法是从应用程序导入路由器并使用 router.registry.extend 方法。
首先在 routers.py 中,我将为路由器命名一个唯一的名称,以避免合并时发生名称冲突
router_store = DefaultRouter()
router_store.register('items', ItemViewSet)
router_store.register('purchases', PurchaseViewSet)
router_store.register('receipts', ReceiptViewSet)
然后是主 routers.py,我将导入所有路由器,然后创建一个新路由器并使用它们扩展它 routers.py:
from store.routers import router_store
from accounts.routers import router_accounts
router = DefaultRouter()
router.registry.extend(router_store.registry)
router.registry.extend(router_accounts.registry)
关于python - Django REST API - 是否可以为每个应用程序创建一个 routers.py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60471704/