gpt4 book ai didi

python - Django 序列化器将模型字段显示为字典

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:44 25 4
gpt4 key购买 nike

抱歉,刚接触 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

谢谢!

最佳答案

您可以添加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)

关于python - Django 序列化器将模型字段显示为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36918905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com