Additional (non model) fields in ModelSerializer (inconsistent with Django forms)

2,786 views
Skip to first unread message

Kai Schlamp

unread,
May 15, 2013, 6:38:01 AM5/15/13
to django-res...@googlegroups.com
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

Matthieu Neamar

unread,
May 15, 2013, 6:57:49 AM5/15/13
to django-res...@googlegroups.com
Hi,

I had the same problem.

I ended up overriding restore_object() and removing the key from the `attr` parameter.

I agree with you however, your syntax looks much better


--
You received this message because you are subscribed to the Google Groups "django-rest-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Kai Schlamp

unread,
May 15, 2013, 4:39:59 PM5/15/13
to django-res...@googlegroups.com
I opened an issue / feature request ... https://github.com/tomchristie/django-rest-framework/issues/840
Reply all
Reply to author
Forward
0 new messages