Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update/append serializer.data in Django Rest Framework [duplicate]

Tags:

How can I update/append serializer.data in Django Rest Framework?

data = serializer.data.update({"item": "test"}) not working

return Response(serializer.data, status=status.HTTP_201_CREATED)

serializer.data is <class 'rest_framework.utils.serializer_helpers.ReturnDict'>

like image 442
user4812479812 Avatar asked May 09 '16 08:05

user4812479812


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

Do we need Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is serializing in Django?

Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).


1 Answers

Unfortunately, serializer.data is a property of the class and therefore immutable. Instead of adding items to serializer.data you can copy serializer.data to another dict. You can try this:

newdict={'item':"test"} newdict.update(serializer.data) return Response(newdict, status=status.HTTP_201_CREATED) 

Read more about property

like image 80
Mohammed Shareef C Avatar answered Sep 24 '22 21:09

Mohammed Shareef C