Understanding basename
Understanding and Using basename
in Django REST Framework
The basename
is specifically used in Django REST Framework (DRF) within the context of routers, particularly when registering viewsets
with the router. It helps the router generate the correct names for URL patterns that correspond to the actions in the viewsets.
When to Use basename
-
When you have multiple viewsets for the same model: Use basename to differentiate the URL names for each viewset.
-
When you want custom URL names: Use basename to create more meaningful or specific names for reverse lookups.
-
When your viewset does not have a queryset: Use basename to ensure DRF can generate URL names, as it can't infer the name without a model.
Multiple ViewSets for the Same Model
Suppose you have another viewset that handles books differently, like ArchivedBookViewSet
, but it still operates on the same Book
model. Here, the basename
becomes essential to avoid name conflicts and to distinguish between the viewsets.
class ArchivedBookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.filter(is_archived=True)
serializer_class = BookSerializer
When you register both viewsets, you need to use different basename
values to avoid conflicts and to create meaningful URL names.
router = DefaultRouter()
# Standard books
router.register(r'books', BookViewSet, basename='books')
# Archived books
router.register(r'archived-books', ArchivedBookViewSet, basename='archivedbooks')
urlpatterns = [
path('', include(router.urls)),
]
In short, use basename
whenever you need to control or customize the URL names generated by DRF, especially in cases with multiple viewsets for the same resource or custom views that don’t directly tie to a model.