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..
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 .
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.
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.
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.
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With