Python Django序列化程序将模型字段显示为字典
我很抱歉,刚到Django的人。我一直在翻阅文档,没有找到这个问题的答案 我有一个模型“Foo”,它有一个字段“bar”,这是一个字典,我将它作为JSON存储在一个TextField中。我希望GET请求将此字段显示为字典,但当我发出请求时,字典将显示为JSON格式的单个字符串 要总结我的代码: 型号:Python Django序列化程序将模型字段显示为字典,python,json,django,dictionary,django-models,Python,Json,Django,Dictionary,Django Models,我很抱歉,刚到Django的人。我一直在翻阅文档,没有找到这个问题的答案 我有一个模型“Foo”,它有一个字段“bar”,这是一个字典,我将它作为JSON存储在一个TextField中。我希望GET请求将此字段显示为字典,但当我发出请求时,字典将显示为JSON格式的单个字符串 要总结我的代码: 型号: class Foo(models.Model): bar = models.TextField(blank=True, default="{}") def getBar(self)
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
class傻瓜列表(generics.ListAPIView):
queryset=[]
对于foo.objects.all()中的foo:
foo.bar=json.load(foo.bar)
#此处foo.bar的打印类型给出“类型”
queryset.append(foo)
serializer\u class=FooSerializer
谢谢 您可以向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)