Skip to content Skip to sidebar Skip to footer

List Serializer With Dynamic Fields In Django Rest Framework

I'm trying to add fields dynamically to a serializer of Django Rest Framework, by overwriting the __init__ method. The approach is similar to the one described here: http://masnun.

Solution 1:

Because VariableDetailSerializer is nested in ParentSerializer it behaves a like a field itself. In this scenario you can override the to_representation() method to do the dynamic type switching.

defto_representation(self, instance):
    field_type = self.TYPE_FIELD_MAP[instance.type_]
    self.fields['value'] = field_type()
    try:
        del self._readable_fields  # Clear the cacheexcept AttributeError:
        passreturnsuper().to_representation(instance)

The main catch here is that the serializer caches the fields because it does not expect them to change between instances. Therefore it is necessary to clear the cache with the del self._readable_fields.

When I add the above to VariableDetailSerializer and run your example, I get:

{
    'variable_details': [
        OrderedDict([('name', u'character value'), 
                     ('type_', u'string'), 
                     ('value', u'hello world')]), 
        OrderedDict([('name', u'integer value'), 
                     ('type_', u'integer'), 
                     ('value', 123)])
    ]
}

Post a Comment for "List Serializer With Dynamic Fields In Django Rest Framework"