Django — Routers
DefaultRouter
from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
SimpleRouter
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
Custom Prefix
router.register(r'posts', PostViewSet, basename='post')
Nested Routers
from rest_framework_nested.routers import NestedSimpleRouter
router = DefaultRouter()
router.register(r'posts', PostViewSet)
nested_router = NestedSimpleRouter(router, r'posts', lookup='post')
nested_router.register(r'comments', CommentViewSet, basename='post-comments')
Generated URLs
| URL | Method | Action |
|---|---|---|
| /api/posts/ | GET | list |
| /api/posts/ | POST | create |
| /api/posts/{id}/ | GET | retrieve |
| /api/posts/{id}/ | PUT | update |
| /api/posts/{id}/ | DELETE | destroy |
Mini Practice
- Set up DefaultRouter
- Use SimpleRouter
- Create custom basename
- Implement nested routers
Up Next
Congratulations! You've completed the Django course. Continue exploring advanced Django topics.
Related Topics
Frequently Asked Questions about Routers
What is Routers in Django?
Routers is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Routers?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Routers.
Why is Routers important in Django?
Routers is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.