0
0
DjangoHow-ToBeginner · 4 min read

How to Use Router in DRF in Django: Simple Guide

In Django REST Framework, use routers to automatically generate URL patterns for your viewsets by registering them with a DefaultRouter. This simplifies routing by handling common CRUD URLs without manual URL definitions.
📐

Syntax

The basic syntax to use a router in DRF involves importing DefaultRouter, creating an instance, and registering your viewset with a URL prefix. Then include the router URLs in your project's urls.py.

  • DefaultRouter(): Creates a router that automatically generates standard RESTful routes.
  • register(prefix, viewset): Connects a viewset to a URL prefix.
  • Include router.urls in your URL patterns to activate the routes.
python
from rest_framework.routers import DefaultRouter
from myapp.views import MyModelViewSet
from django.urls import path, include

router = DefaultRouter()
router.register(r'mymodels', MyModelViewSet, basename='mymodel')

urlpatterns = [
    path('', include(router.urls)),
]
💻

Example

This example shows a simple Django REST Framework setup using a router to expose CRUD endpoints for a model called Book. The router automatically creates URLs like /books/ and /books/{id}/ for list, create, retrieve, update, and delete actions.

python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework import viewsets
from rest_framework import serializers
from myapp.models import Book

# Serializer for Book model
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author']

# ViewSet for Book
class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

# Router setup
router = DefaultRouter()
router.register(r'books', BookViewSet, basename='book')

# URL patterns
urlpatterns = [
    path('', include(router.urls)),
]
Output
GET /books/ -> List all books POST /books/ -> Create a new book GET /books/{id}/ -> Retrieve a book by id PUT /books/{id}/ -> Update a book DELETE /books/{id}/ -> Delete a book
⚠️

Common Pitfalls

Common mistakes when using routers in DRF include:

  • Not including router.urls in your urlpatterns, so routes don't work.
  • Registering a viewset without a basename when the queryset is missing or dynamic, causing errors.
  • Using SimpleRouter when you need the default root API view, which DefaultRouter provides.
  • Manually defining URLs that conflict with router-generated URLs.
python
from rest_framework.routers import DefaultRouter
from myapp.views import MyViewSet
from django.urls import path, include

router = DefaultRouter()
# Wrong: missing basename when queryset is not defined
# router.register(r'myview', MyViewSet)

# Right:
router.register(r'myview', MyViewSet, basename='myview')

urlpatterns = [
    # Wrong: forgetting to include router.urls
    # path('api/', include('myapp.urls')),

    # Right:
    path('api/', include(router.urls)),
]
📊

Quick Reference

Summary tips for using DRF routers:

  • Use DefaultRouter for automatic CRUD URL generation and a root API view.
  • Register each viewset with a URL prefix and a basename if queryset is missing.
  • Include router.urls in your main urls.py to activate routes.
  • Do not manually define URLs that overlap with router-generated ones.

Key Takeaways

Use DefaultRouter to automatically create RESTful URLs for your viewsets.
Always include router.urls in your urlpatterns to enable routing.
Provide a basename when registering viewsets without a queryset attribute.
Avoid manually defining URLs that conflict with router-generated routes.
DefaultRouter also provides a default API root view listing all registered routes.