Muhammad Hassan
Muhammad Hassan

Reputation: 14391

How to Make Different Urls For same viewset in Django Rest Framework

I have a Serializer in my code like this

class SampleSerializer(serializers.ModelSerializer):
      class Meta:
            model = Model

and Viewset like this

class SampleViewSet(GenericAPIView):
     serializer_class = SampleSerializer

     def get(self, request, *args, **kwargs):
         pass

     def post(self, request, *args, **kwargs):
         pass

     def put(self, request, *args, **kwargs):
         pass

I have url like this for this viewset

Url #1:

url(r'^sample/$', SampleViewSet.as_view())

This makes url for all methods I have in my viewset like get, post and put etc. I want to make separate url for my get method but using same serializer. This url will look like this

Url #2:

 url(r'^sample/(?P<model_id>\d+)/$', SampleViewSet.as_view())

How can I do this using same Viewset and Serializer? When I write Url #2 in urls.py, Swagger shows me all three type (get, post and put) of methods for that Url.

Upvotes: 2

Views: 8958

Answers (2)

Antash
Antash

Reputation: 998

You could use require_GET decorator from django.views.decorators.http for this, and use it in your URL config:

urlpatterns = [
    url(r'^sample/$', SampleViewSet.as_view()),
    url(r'^sample/(?P<model_id>\d+)/$', require_GET(SampleViewSet.as_view())),
]

for more fine tuning there is also a require_http_method decorator which receives allowed methods in its parameters, e.g.:

url(r'^sample/(?P<model_id>\d+)/$', require_http_method(['GET', 'DELETE'])(SampleViewSet.as_view()))

See https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-in-urlconf for details.

Upvotes: 6

Ivan Semochkin
Ivan Semochkin

Reputation: 8907

Why don't you inherit ViewSet from viewsets.ViewSet and map your urls view DefaultRouter?

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'sample', SampleViewSet)
urlpatterns = router.urls

It will handle all urls for your. /sample/:id now will be available for GET, PUT and DELETE methods.
Also if it plain CRUD for your Sample model, there is a better solution to use a viewsets.ModelViewset.

Upvotes: 2

Related Questions