【问题标题】:Django Serializer Display Model Field as DictionaryDjango 序列化程序将模型字段显示为字典
【发布时间】:2016-08-23 11:13:43
【问题描述】:

抱歉,Django 新手。我一直在搜索文档,但无法找到答案。

我有一个模型“Foo”,它有一个字段“bar”,它是我在 TextField 中存储为 JSON 的字典。我想要一个 GET 请求将此字段显示为字典,但是当我发出请求时,字典以 JSON 格式显示为单个字符串。

总结一下我的代码:

型号:

class Foo(models.Model):
    bar = models.TextField(blank=True, default="{}")
    def getBar(self):
        return json.loads(bar)

序列化器:

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = ("bar")
        read_only_fields = ("bar")
    def create(self, data):
        return Foo.objects.create(**data)

观看次数:

class FooList(generics.ListAPIView):
    queryset = []
    for foo in Foo.objects.all():
        foo.bar = json.loads(foo.bar)
        # Printing type of foo.bar here gives "type <dict>"
        queryset.append(foo)
    serializer_class = FooSerializer

谢谢!

【问题讨论】:

    标签: python json django dictionary django-models


    【解决方案1】:

    您可以将SerializerMethodField 添加到您的 ModelSerializer 类中,如下所示:

    class FooSerializer(serializers.ModelSerializer):
        class Meta:
            model = Foo
            fields = ('bar',)
            read_only_fields = ('bar',) # Not required, because 
                                        # SerializerMethodField is read-only already
    
        bar = serializers.SerializerMethodField('get_bar_dict')
    
        def get_bar_dict(self, obj):
            return json.loads(obj.bar)  # This gets the dict and returns it
                                        # to the SerializerMethodField above
    
        # Below is the rest of your code that I didn't touch
        def create(self, data):
            return Foo.objects.create(**data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      相关资源
      最近更新 更多