我正在尝试超越 Django REST Frameworks 初始平面 URL 模式。例如,如果我有对象类型 parentobject 和 childobject,其中 parentobject HAS childobject(s) 那么开箱即用的 REST 如下。
^ ^api/ ^ ^parentobject/$ [name='parentobject-list']
^ ^api/ ^ ^parentobject/\.(?P<format>[a-z]+)$ [name='parentobject-list']
^ ^api/ ^ ^parentobject/(?P<pk>[^/]+)/$ [name='parentobject-detail']
^ ^api/ ^ ^parentobject/(?P<pk>[^/]+)/\.(?P<format>[a-z]+)$ [name='parentobject-detail']
^ ^api/ ^ ^childobject/$ [name='childobject-list']
^ ^api/ ^ ^childobject/\.(?P<format>[a-z]+)$ [name='childobject-list']
^ ^api/ ^ ^childobject/(?P<pk>[^/]+)/$ [name='childobject-detail']
^ ^api/ ^ ^childobject/(?P<pk>[^/]+)/\.(?P<format>[a-z]+)$ [name='childobject-detail']
在 parentobject 响应中,将引用 childobject(s) id。
GET /api/parentobject/1/
(results in)
{
"childobject": [123, 456, 789]
}
如果您想要有关 childobject(或 db 中的所有 childobjects)的详细信息,您可以引用 childobject api。
/api/childobject/
/api/childobject/123/
还在同一个页面上? :)
我想要做的是创建一种通用/可扩展的方式,通过 parentobject api 引用子 m2m 关系,而不必拉 id,然后重新查询 childobject api。
/api/parentobject/1/childobject/
[
{
"childobject_prop": 1
...etc
}
]
因此,以上将是基于 m2m 中的父对象引用过滤的子对象,通过 Django 管理的表。
这个想法也是通用的,因为我可以定义一个新的直通关系,并以最少的工作拥有这种能力。例如url 模式将是自动的,等等。
此外,任何降序关系都将以相同的方式处理。这样下面的“someotherchildobject”将返回映射到子对象“123”、映射到父对象“1”的某个子对象的列表。
/api/parentobject/1/childobject/123/someotherchildobject/
如果这还不够清楚,请告诉我。到目前为止,我的成功是有限的。我不想修改 Django REST 来实现这一点,同时我不想通过将我感兴趣的特定模式添加到 urlpatterns 中来“手动”构建 URL 模式。
另外,作为奖励,我希望这适用于 Django 中的 CUSTOM through= 表;并将直通表上的任何其他字段映射到返回数据 similar to this 中的字段。
谢谢!
最佳答案
你应该调查https://github.com/alanjds/drf-nested-routers/
这已在 https://github.com/tomchristie/django-rest-framework/pull/1048 中提出
关于django - Django REST Framework 中的嵌套 URL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217044/