[Django]-How to manage views,urls and models on large scale in Django?

2πŸ‘

βœ…

You can create a package called views. Then you can create a separate file for each view and import each one of them into __init__.py of views package. Doing that you are still able to import views as previously.

my_app.
β”œβ”€β”€ views
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ my_view.py

Then in my_view.py:

def my_view(request):
    pass

And in the __init__.py:

from my_app.views.my_view import my_view

In all other files, you can import my_view like this:

from my_app.views import my_view

The same can be done for models, URLs, …

2πŸ‘

In my experience in different projects and teams, we did it in this way:

application
β”œβ”€β”€ api
β”‚Β Β  β”œβ”€β”€ __init__.py
β”‚Β Β  β”œβ”€β”€ urls.py
β”‚Β Β  └── v1
β”‚Β Β      β”œβ”€β”€ __init__.py
β”‚Β Β      β”œβ”€β”€ view_a.py
β”‚Β Β      β”œβ”€β”€ ...
β”‚Β Β      β”œβ”€β”€ view_z.py
β”‚Β Β      └── urls.py
β”œβ”€β”€ apps.py
...

I keep my views in different versions, so we can support backward compatibilities in APIs and Views.
You have to create a Python Package (a directory including an __init__ file); And just import everything you want to export from that package.

For example, in application/api/v1/__init__.py:

from .view_a import FooListView
from .view_b import BarDetailView

And, of course, you can create classes inside the __init__ file too. Everything you write in it is accessible from the Package’s name directly instead of the views’ file name.

Don’t forget to keep versioning your APIs in urls.py too.

# api/urls.py
from django.urls import path, include

urlpatterns = [
    path('v1/', include('application.api.v1.urls')),
    path('v2/', include('application.api.v2.urls')),
    ...
]
# api/v1/urls.py
from django.urls import path

from . import *  # this imports every view classes from __init__.py file
                 # Or you can just import directly from views instead
                 # of having an __init__ file:
                 # from .view_a import FooListView

urlpatterns = [
    path('foo/', FooListView.as_view()),
    ...
]

πŸ‘€itismoej

Leave a comment