</>
Skip to content
Django lessons (43/43)

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

URLMethodAction
/api/posts/GETlist
/api/posts/POSTcreate
/api/posts/{id}/GETretrieve
/api/posts/{id}/PUTupdate
/api/posts/{id}/DELETEdestroy

Mini Practice

  1. Set up DefaultRouter
  2. Use SimpleRouter
  3. Create custom basename
  4. 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.