0

I have some model:

class Settings(mongoengine.Document):
    name = mongoengine.StringField()
    range = mongoengine.DynamicField()

And serializer for it:

class SettingsSerializer(serializers.DocumentSerializer):
    class Meta:
        model = Settings
        fields = [
            'name',
            'range'
        ]

Field 'range' can be a dict or list. But, when I do serialize I got only string to this field:

{
"name": "hello world",
"range": "{'max': 100, 'min': 0}",
}

How can I get list or dict after serialize?

Mike
  • 860
  • 14
  • 24

1 Answers1

1

You can do that with python eval's method and DRF SerializerMethodField.

Try this.

from rest_framework import serializers as drf_serailizer

class SettingsSerializer(serializers.DocumentSerializer):
    range = drf_serailizer.SerializerMethodField()

    class Meta:
        model = Settings
        fields = [
            'name',
            'range'
        ]

    def get_range(self, object):
        try:
            return eval(object.range)
        except:
            return None
Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
  • I got error: AttributeError: module 'rest_framework_mongoengine.serializers' has no attribute 'SerializerMethodField' – Mike Feb 08 '17 at 11:45
  • hmm you are using mongo serializer. Can you try out the update code. I have imported django rest framework serializer with a different name – Bipul Jain Feb 08 '17 at 11:51