Django Rest Framework组织ViewSets和路由器 [英] Django Rest Framework organizing ViewSets and Routers

查看:242
本文介绍了Django Rest Framework组织ViewSets和路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题可能是组织ViewSets和Django Rest Framework中相应的路由器时的最佳实践。

Hi there so my question is probably about best practices when organizing ViewSets and the corresponding Routers in Django Rest Framework.

根据官方文档,路由器应该是存储在 urls.py 中,并且视图应存储在 views.py 中。

According to the official documentation, the routers should be stored in the urls.py and the viewsets should be stored in views.py.

我的想法是将视图集合到一个单独的文件中,例如 viewsets.py ,以便我们不会在同一个文件中混合正常的Django视图和DRF视图集,从而提高可读性。

My idea of an approach would be having the viewsets in a separate file like for example viewsets.py so that we don't end up mixing the normal Django views and the DRF Viewsets in the same file, improving readability.

同样的路由器将会在那里进行复制每个应用程序内的文件称为路由器,然后使用主要的默认路由器实例注册。

The same would go for the routers where we would creaate a file called routers inside each app and register then with the main Default router instance.

这些是我的想法,但是我不知道如何:

These are my thoughts, but i am not sure how to:

1º这样做是正确的方式(注册视图路由器和所有,我应该将DefaultROuter放在 __init __。py ?)

1º Do this the proper way (the registering of the viewsets routers and all, should i place DefaultROuter in the __init__.py ?)

2º是否有更好的方法?

2º Is there a better approach?

我想分开每个应用程序和每个应用程序内部的逻辑,由django视图和DRf视图分开。

Basically i want to separate the logic per app and inside each app separate by django views and DRf viewsets

推荐答案

对于什么是值得的我总是在我的Django应用程序中创建一个单独的api /子目录来保存所有Dj ango REST框架相关文件。这只是一种做事的方法,但它有助于在我们的应用程序中保持分离。

For what it's worth, I've always created a separate api/ subdirectory within my Django apps to hold all Django REST Framework related files. This is just one way of doing things but it's helped keep separation of concerns within our applications.

层次结构看起来像这样...

The hierarchy looked like this...


  • Django项目/

    • Django App /

      • py

      • models.py

      • urls.py

      • api /

        • serializers.py

        • viewsets.py

        • Django Project/
          • Django App/
            • views.py
            • models.py
            • urls.py
            • api/
              • serializers.py
              • viewsets.py

              这篇关于Django Rest Framework组织ViewSets和路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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