66👍
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)
9👍
Alternatively you might use SerializerMethodField to add additional data by adding a custom method to the serializer.
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
You can use such a method to return any data, wether in context of the model or not.
class UserSerializer(serializers.ModelSerializer):
days_since_joined = serializers.SerializerMethodField()
class Meta:
model = User
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
- [Django]-Project design / FS layout for large django projects
- [Django]-How to clear the whole cache when using django's page_cache decorator?
- [Django]-Django rest framework lookup_field through OneToOneField
8👍
You don’t.
If you need to pass extra data to the serializer’s create/update please do so while calling serializer.save() as explained in the documentation
- [Django]-Check if model field exists in Django
- [Django]-Django multiprocessing and database connections
- [Django]-Is there something similar to 'rake routes' in django?
5👍
We can update the data passed in response with serializer._data
sample code
class SampleAPIView(generics.CreateAPIView)
serializer_class = SampleSerializer
def perform_update(self, serializer):
application = serializer.save(status='pending')
my_response_data = {'id': 110, 'name': 'Batta'}
serializer._data = out_data
serializer._data
will make the magic.
Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L260
- [Django]-Is there a django template filter to display percentages?
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
- [Django]-Access Django models with scrapy: defining path to Django project
4👍
The serializer.data
object is a instance of ReturnList that is immutable. What you can do to workaround this limitation is transform the serializer.data
object into a simple Python list(), then append the value you want so you can use your transformed list in Response() method like this:
def get(self, request):
serializer = YourAmazingSerializer(many=True)
new_serializer_data = list(serializer.data)
new_serializer_data.append({'dict_key': 'dict_value'})
return Response(new_serializer_data)
Then, your response will have your new obj
- [Django]-Find Monday's date with Python
- [Django]-Request.data in DRF vs request.body in Django
- [Django]-Naming Python loggers