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()),
...
]
- [Django]-Daemonizing celery process celeryd-multi not found
- [Django]-How to add an extra field to a Django ModelForm?
- [Django]-AttributeError in views.py: type object 'Transaction' has no attribute 'objects'