Django ModelViewSet is a straight forward way for CRUD with a Single serialiser, but there can be instances where you need to use different serialisers for create function or any other.
You have two options.
- Define a function to override functions of
ModelViewSet
and use different serialiser inside the function. - Use
get_serializer_class
to provide different serialiser depending on the request method.
Overriding function
In here create
overrides the default object class of ModelViewSet
and rest Is defined in the function.
class YourModelViewSet(viewsets.ModelViewSet):
queryset = YourModel.objects.filter()
serializer_class = YourModelSerializer
permission_classes = (permissions.IsAuthenticated)
def create(self):
serializer = YourModelSerializer_2(data=request.data)
yourdata = serialiser.save()
get_serializer_class
If you don't want to mess up the pre-packed functions of DRF but want each request to use a different serialiser this is the way to go.
class YourModelViewSet(viewsets.ModelViewSet):
queryset = YourModel.objects.filter()
serializer_class = YourModelSerializer
permission_classes = (permissions.IsAuthenticated)
def get_serializer_class(self):
if self.action == 'list':
return YourModelSerializer_2
return YourModelSerializer
Last 5 Articles
All Articles >
-
9 Ways to Boost the Design of Your Sports Team Website
-
DevOps Tools
-
The Best Marketing Apps to Use with Shopify
-
Tips to Increase Software Development Speed
-
Mitigating Risks In Custom Software Development
News Letter
Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.
Comments
Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ
rel="nofollow"
for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.