How do i rewrite my code with Routers? Django rest framework

320 views Asked by At

I have this REST API:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', UserViewSet.as_view({'get': 'list', 
                                        'post': 'create', 
                                        'delete': 'delete'})),
    path('users/<uuid:pk>/video/', UserViewSet.as_view({'post': 'video'}))
]

How can i rewrite this with routers?

Default router with register method creates API -> GET users/ and POST users/ and also DELETE /users/{id} but it's different from current, because i need DELETE /users/ endpoint.

Or, maybe, in this situation it would be more correct to use my code with dictionaries?

1

There are 1 answers

5
jackdek11 On

assuming that UserViewSet is indeed a viewset, you can use the restframework's default router to register the router for /users/, and then add an action to handle you /video/ route from that viewset.

urls.py

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'users/', UserViewSet, basename='users')

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += router.urls

viewsets.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (
    CreateModelMixin, RetrieveModelMixin, 
    DestroyModelMixin, ListModelMixin
)
from rest_framework.decorators import action
from rest_framework.parsers import MultiPartParser

class UserViewSet(CreateModelMixin, RetrieveModelMixin, 
                  DestroyModelMixin, ListModelMixin, GenericViewSet):
    # serializer class
    # queryset
    # permissions

    @action(methods=['post'], parser_classes=(MultiPartParser,), detail=True)
    def video(self, request, pk=None, *args, **kwargs):
        # Implementation to upload a video

Edit

To create a bulk DELETE of users endpoint, I would create a Mixin class, as there is no django mixin for Deleting on the index of a router..

class BulkDeleteModelMixin:
    def destroy(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        self.perform_destroy(queryset)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, 
                        status=status.HTTP_201_CREATED, headers=headers)

    def perform_destroy(self, queryset):
        queryset.delete()

And inherit from this class in your viewset

viewsets.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (CreateModelMixin, RetrieveModelMixin, ListModelMixin)
from some_app.mixins import BulkDeleteModelMixin

class UserViewSet(CreateModelMixin, RetrieveModelMixin, 
                  BulkDeleteModelMixin, ListModelMixin, GenericViewSet):