Skip to content

Instantly share code, notes, and snippets.

@dmwyatt
Last active October 25, 2023 22:08
Show Gist options
  • Save dmwyatt/93f36c7efa9f9d7685cd to your computer and use it in GitHub Desktop.
Save dmwyatt/93f36c7efa9f9d7685cd to your computer and use it in GitHub Desktop.
[auto drf url registration] Using Django Rest Framework's DefaultRouter to build an API Root for urls.py files located in individual apps. #django #drf
# urls.py
def register_routes(router, apps):
"""
Register DRF router routes from urls.py in the provided apps.
>>> router = routers.DefaultRouter()
>>> register_routes(router, ['app1', 'app2', 'app3])
"""
for app in apps:
urls = importlib.import_module(app+".urls")
try:
routes = urls.routes
except AttributeError:
continue
for route in routes:
router.register(*route)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment