python - Overide serializer.data in Django REST Framework -
i've been trying alter value of form field django rest framework's admin panel , reason change never takes place. have serializer below
class someview(modelviewset): queryset = mymodel.objects.all() serializer_class = mymodelserializer # want override , change post data def perform_create(self, serializer): user = self.request.user.id # form field manually entered user id # want default logged in user serializer.data['user'] = user # returns original user entered form field print serializer.data
i checked out serializer.data dir()
, it's python dictionary can't figure out why can't modify value. test tried add values doesn't work either
# doesnt work serializer.data['some_new_field'] = 'test'
edit
on note, can copy data , edit it
fake_data = serializer.data.copy() fake_data['old_value'] = 'new value'
however fails validate
serializer = mymodelserializer(data=fake_data) serializer.is_valid() # returns false
edit edit:
ok, validation error caused django returning simplelazyobject. works when perform copy on data, i'm curious why can't edit serializer.data
directly without copying it. problem solved now, if can provide insight on issue curiosity, awesome.
i checked out serializer.data dir() , it's python dictionary can't figure out why can't modify value.
while value return serializer.data
indeed dictionary, serializer.data
not simple instance variable.
if @ rest_framework/serializers.py
:
class serializer(baseserializer): # [...] @property def data(self): ret = super(serializer, self).data return returndict(ret, serializer=self)
returndict
inherits ordereddict
, still new dictionary every time access serializer.data
.
the real data in _data
, noted underscore might not want modify either not intended public. values filled serializer.to_representation()
override on viewset.
as second part: modelviewset
defines get_serializer()
called request post data create serializer want modify. i'd suggest try change input data before serializer created, instead.
Comments
Post a Comment