python - Django REST API - 是否可以为每个应用程序创建一个 routers.py?

标签 python django python-3.x django-rest-framework

您好,我已经设置了一个包含 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/

相关文章:

django:在保存目标模型之前分配外键

Python:将原始字符串转换为字节字符串而不添加转义字符

python-3.x - 在 `setup.py` 或 `pyproject.toml` 中指定 Python PIP 参数

python-3.x - 检查python字符串是否包含特定字符

python - 无法在 ubuntu 中安装 lxml verison 3.3.5

python - 在另一个类函数中使用一个类的条目

python - 通过将两个字典的值合并到排序列表中来组合两个字典

python - Django transaction.commit_on_success 不回滚事务

python - 使用 <a> 标签过滤

django - 两个独立的 Django 应用程序需要相同的模型