White
White

Reputation: 134

Django url patterns: good practice?

I am wondering whether the following is considered "bad practice". I have multiple urls.py files per app in a Django project. So for example I have in a single app called locations I may the following files:

# locations/urls/api.py
# locations/urls/general.py

Both of these are included in "main url file":

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

urlpatterns = [
    # ... snip ...
    path('api/locations', include('locations.urls.api')),
    path('locations/', include('locations.urls.general')),
    # ... snip ...
]

The reason I am considering this construction is because I want some "location urls" to be within the api/... routes combined with routes coming from other apps into the api/... routes and some I would like to be just within the locations/... routes.

I hope my explaination is clear. Let me know what you think of this construction!

Cheers!

Upvotes: 0

Views: 1321

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

You don't actually need them to be in separate files. include can include a list of patterns: so you could do:

api_urlpatterns = [
    path(...),
    path(...),
]
general_urlpatterns = [
    path(...),
    path(...),
]

urlpatterns = [
    # ... snip ...
    path('api/locations', include(api_urlpatterns)),
    path('locations/', include(general_urlpatterns)),
    # ... snip ...
]

Upvotes: 5

Related Questions