When using additional fields in a ModelSerializer (see below for an example) that are not available as attributes in the model itself, it will throw an TypeError (full error below) during deserialization as the serializer seems to force to build an object with that attribute. Django forms are much more tolerant in this case. If one deletes that field from the attrs array in clean_additional_info everything works ok.
I often have the case that I need additional stuff in an API post (create) request that is not directly represented in the model (but changes several other attributes in the model). How to do it with the REST Framework? Is the only way to overwrite restore_object in ModelSerializer? (Another option is to introduce virtual attributes in the model, but I don't like this idea.)
Kind regards,
Kai
# My serializer
class PostSerializer(serializers.ModelSerializer):
additional_info = serializers.WritableField() # no corresponding model property
class Meta:
model = Post
fields = ('title', 'content', 'additional_info',)
def validate_additional_info(self, attrs, source):
value = attrs[source]
# do something with value (maybe adjust existing model properties)
del attrs[source]
return attrs
# The exception
File "/home/user/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/site-packages/rest_framework/serializers.py", line 787, in restore_object
instance = self.opts.model(**attrs)
File "/home/user/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/site-packages/django/db/models/base.py", line 415, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'additional_info' is an invalid keyword argument for this function