我道歉,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
谢谢!
答案 0 :(得分: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)