Django rest框架嵌套了视图集和路由 [英] Django rest framework nested viewsets and routes

查看:108
本文介绍了Django rest框架嵌套了视图集和路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以嵌套视图集并创建将 pk 作为URL参数的路由吗?

Can i nest the viewsets and create routes that takes pk as parameters of the url?

基本上是:

class TaskView(viewsets.ModelViewSet):
    model = Task

这很好用,并且映射到 task / 网址,所以 task / 1 / 给出ID为1的任务的数据。现在,我想创建该任务的 instance ,并进行CRUD操作对于该任务,所以我想要拥有

this works fine and it's mapped to the task/ url, so task/1/ gives the data of the task with id 1. now, i want to create an instance of the task, having CRUD operations as for the task, so i would like to have

class InstanceView(viewsets.ModelViewSet):
        model = Instance

映射到任务/ {pk} /实例,其中 pk 是任务的ID。

mapped to task/{pk}/instance, where pk is the id of the task.

我该怎么做?可能吗?
PS:我看到有 @action @link ,但是使用它们我失去了

how can i do that? is it possible? PS: i saw that there are @action and @link but using them i loose the power of having everything made by the framework.

推荐答案

有两个插件可以实现此目的: drf-nested-viewsets drf-nested-routers

There are two plugins out there for making this happen: drf-nested-viewsets and drf-nested-routers.

DRF嵌套路由器在路由器级别工作,使嵌套视图集变得容易,因为将嵌套参数传递到每个方法中以方便参考。存储库中的自述文件概述了可以完成的工作。似乎不允许嵌套的DefaultRouters(包括API根页面)。

DRF Nested Routers works on a router level and makes it easy to do nested viewsets, as the nested parameters are passed into every method for easy reference. The README in the repository gives an overview of what can be done. This does not appear to allow for nested DefaultRouters (which include the API root page).

DRF嵌套视图集(完全公开:由我创建)主要用于超链接方案(所有内容均使用HyperlinkedModelSerializer),并且使用起来并不容易。它通过映射当前的URL参数以在链接的模型上生成嵌套的url,从而处理超链接关系。可以在原始要点中找到一些文档。

DRF Nested Viewsets (full disclosure: created by me) is primarily meant for hyperlinked scenarios (where everything uses a HyperlinkedModelSerializer) and isn't as easy to use. It handles hyperlinked relations by mapping the current URL arguments to generate nested urls on linked models. A bit of documentation is available at the original gist.

两个插件都需要重写 get_queryset 来过滤嵌套查询集。对于DRF嵌套视图集,这需要从视图集中的 self.kwargs 中提取url参数并使用它们进行过滤,我不确定如何使用DRF嵌套路由器来完成此操作,但是

Both plugins require overriding get_queryset for filtering nested querysets. For DRF Nested Viewsets this requires pulling url arguments from self.kwargs within the viewset and using those to filter, I am not sure how it is done using DRF Nested Routers, but it mostly likely isn't much different.

注意:如果您不需要超链接关系,则可以在没有第三方插件的情况下完成此操作只是覆盖 get_queryset 并过滤掉url参数。

Note: If you do not need hyperlinked relations, this can be done without third-party plugins by just overriding get_queryset and filtering off of url arguments.

这篇关于Django rest框架嵌套了视图集和路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆