Login

Different Response Data/Serializer for DRF Views/Viewsets

Author:
shivanshs9
Posted:
December 12, 2018
Language:
Python
Version:
2.0
Score:
0 (after 0 ratings)

Mixin for Django Rest Framework View/Viewsets to use different response data/serializers without unnecessary hacks.

Just extend your DRFs view/viewset with this mixin after the DRF's APIView (sub)classes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class UnsafeResponseSerializerMixin(object):
	"""
	Apply this mixin to any view or viewset to automatically use a different response
	serializer on POST, PUT or PATCH requests.
	
	Override 'get_response_data' method to return back the desired data, or 
	'get_response' method to also provide additional changs to the returned Response.
	"""

	def get_response_data(self, request):
		pass

	def get_response(self, request, response):
		data = self.get_response_data(request)
		if data:
			response.data = data
		return response

	def __init__(self, **kwargs):
		super(UnsafeResponseSerializerMixin, self).__init__(**kwargs)
		if hasattr(self, 'post'):
			self.post = self._post
		if hasattr(self, 'put'):
			self.put = self._put
		if hasattr(self, 'patch'):
			self.patch = self._patch

	def _post(self, request, *args, **kwargs):
		response = super(UnsafeResponseSerializerMixin, self).post(request, *args, **kwargs)
		return self.get_response(request, response)

	def _put(self, request, *args, **kwargs):
		response = super(UnsafeResponseSerializerMixin, self).put(request, *args, **kwargs)
		return self.get_response(request, response)

	def _patch(self, request, *args, **kwargs):
		response = super(UnsafeResponseSerializerMixin, self).patch(request, *args, **kwargs)
		return self.get_response(request, response)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.