Meta class for DRF serializer to display JSON data

By | August 30, 2018
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:

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        """Serializer config."""
        json_fields = [('asid', 'ASID'), ...]
        fields = [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.