whoisearth
whoisearth

Reputation: 4170

Django Rest Framework - modify serializer.data

I have a view where I'm doing the following -

def retrieve(self, request, pk=None):
    queryset = MyClass.objects.all()
    class_data = get_object_or_404(queryset, pk=pk)
    serializer = self.get_serializer(class_data)
    new_data = serializer.data.copy()
    new_data['my_field'] = 'updated info!'
    serializer = self.get_serializer(data=new_data)
    serializer.is_valid()
    return Response(serializer.data)

I'd like to not have to make a copy of the serializer data to update the info. Is there a way to modify a field in a serializer before display through the view?

edit -

serializer.data['my_field'] = 'updated info!'

does not work unless I make a copy.

Upvotes: 1

Views: 2959

Answers (2)

Jisson
Jisson

Reputation: 3725

In my case, I need to update the serializer.data with some exta dict. I solved in the following way, Merged the ordered dicts serializer.data[0] and the extra dict.

from itertools import chain
from collections import OrderedDict
class MyCreationApiView(generics.CreateAPIView):
    def create(self, request, *args, **kwargs):
        data = ...
         serializer = self.get_serializer(data=data, many=True, required=True,
                                         context={'request': self.request, 'search': search})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        extra_dict = {'test': []}
 return Response([OrderedDict(chain(serializer.data[0].items(), extra_dict.items()))], status=status.HTTP_201_CREATED).

ref:

Upvotes: 0

Ivan
Ivan

Reputation: 6013

Well the straightforward solution is just to set the retrieved object attribute (class_data.my_field = 'updated info!').

Upvotes: 1

Related Questions