class JSONDataMetaclass(SerializerMetaclass):
"""Meta class to dynamically add SerializerMethodField and look up JSON data"""
def __new__(cls, name, bases, attrs):
for field in getattr(attrs.get('Meta'), 'json_fields', []):
def _(self, obj):
return obj.raw_data.get(field[1])
attrs[field[0]] = serializers.SerializerMethodField()
attrs['get_{}'.format(field[0])] = _
return super(JSONDataMetaclass, cls).__new__(cls, name, bases, attrs)
Then you can use it by:
@six.add_metaclass(JSONDataMetaclass)
class ItemSerializer(serializers.ModelSerializer):
class Meta:
"""Serializer config."""
json_fields = [('asid', 'ASID'), ...]
fields = [...]