序列化DynamicField

时间:2017-02-08 11:07:53

标签: django django-mongodb-engine

我有一些模特:

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

它的序列化器:

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

Field'范围'可以是字典或列表。 但是,当我进行序列化时,我只得到这个字段的字符串:

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

序列化后如何获取列表或词典?

1 个答案:

答案 0 :(得分:1)

您可以使用python eval的方法和DRF SerializerMethodField来实现。

试试这个。

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