Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework, can I use ViewSet to generate a json from django view function?

I know I can use drf serializer from django views, but queryset, pagination setting is all duplicated in drf viewset and django view.

Can I reuse viewset to generate json data and include it in regular django response?

Update:
ie, Can I call ViewSet.as_view()(self.request) from django view?
it's not documented way, so I'm wondering the downsides of this approach .. and if it's doable..

like image 296
eugene Avatar asked Oct 20 '14 07:10

eugene


People also ask

What is the use of ViewSet in Django?

After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet .

What is difference between View and ViewSet in Django?

While regular views act as handlers for HTTP methods, viewsets give you actions, like create or list . The great thing about viewsets is how they make your code consistent and save you from repetition. Every time you write views that should do more than one thing, a viewset is the thing that you want to go for.

What is the difference between APIView and ViewSet?

APIView is the base class based view. Viewsets have APIView as a parent class. With Viewsets, you code more specific methods . For example the 'retrieve' method, will expect arguments of the request and the pk of the object to be retrieved.

How do you serialize an object in Django REST framework?

Creating and Using Serializers To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django.


1 Answers

Yes, you can call YourViewSet.as_view()(self.request) in your Django view.

Make sure you call the ViewSet like below:

YourViewSet.as_view({'get': 'list'})(self.request)

Else it will raise an exception

The actions argument must be provided when calling .as_view() on a ViewSet. For example .as_view({'get': 'list'})

like image 176
Tevin Joseph K O Avatar answered Oct 10 '22 15:10

Tevin Joseph K O