Django REST Framework在另一个ViewSet上添加一个ViewSet作为详细信息 [英] Django REST Framework add a ViewSet as detail on another ViewSet

查看:133
本文介绍了Django REST Framework在另一个ViewSet上添加一个ViewSet作为详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,一个模型和一个注释:

I've got two models, one of a box and one of box comment:

class BoxViewSet(viewsets.ModelViewSet):
queryset = Box.objects.all()
Permission_classes = IsAuthenticated,
serializer_class = BoxSerializer

类BoxCommentViewSet(viewsets.ModelViewSet):
模型= BoxComment
serializer_class = CommentSerializer
Permission_classes = IsAuthenticated
def get_queryset(self):
#这应该返回一个查询集,该查询集将根据路由
中的
#框进行过滤return BoxComment.objects.all()

如果我设置了一个路由器以使Boxs可以在 / boxes / 中使用,而特定的Boxs可以在中使用/ boxes / {id} / 使用

router.register(r'boxes',feed.views.BoxViewSet)

是否可以在 / boxes / {id} / comments / ?还是应该只设置一条单独的路由并使用GET / POST参数来引用特定的框?

If I've set up a router to make Boxes available at /boxes/ and specific boxes available at /boxes/{id}/ using
router.register(r'boxes', feed.views.BoxViewSet)
is it possible to make comments available at /boxes/{id}/comments/? Or should I just set up a separate route and use GET/POST parameters to refer to specific boxes?

推荐答案

用作嵌套路由器(或嵌套视图集),并且在Django REST Framework中通常不建议这样做。如有可能,您应该在API中使用平面表示形式,因此

This is typically referred to as nested routers (or nested viewsets), and it's generally not recommended in Django REST Framework. If possible, you should use a flat representation in your APIs, so

/boxes/{id}/comments

实际上是

/comments/?box={id}

使用Django REST Framework相当容易实现使用内置过滤(和也许是django-filter )。保证不会在DRF的未来版本中中断,并且这是推荐的方式时刻。如果您愿意, HTTP API指南可能是一本好书。对原因很感兴趣,并且那里还有一个对此进行讨论

This is considerably easier to implement with Django REST Framework using the built-in filtering (and maybe django-filter). It's guaranteed not to break in future versions of DRF, and it's the recommended way at the moment. The HTTP API guidelines might be a good read if you're interested why, and there's a discussion about it there as well.

现在,您不能总是避免使用嵌套路由器。我已经使用当时可用的第三方软件包写下了有关过去的信息。从那时起, drf-extensions对其进行了整合,其中包含一个可以在大多数情况下正常工作的嵌套路由器的实现。

Now, you can't always avoid using nested routers. I've written about it in the past, using the third-party packages that were available at the time. Since then, drf-extensions has integrated it and it contains a decent implementation of nested routers that should work for most cases.

这篇关于Django REST Framework在另一个ViewSet上添加一个ViewSet作为详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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