gpt4 book ai didi

django - 使用 Django Rest Framework 将扁平 JSON 转换为嵌套 JSON

转载 作者:行者123 更新时间:2023-12-01 23:24:13 26 4
gpt4 key购买 nike

我的 View 中有一个 json,如下所示,

{
"name":"myname",
"age":30,
"day":20,
"month":"June",
"year":1988
}


如何使用序列化程序将其转换为嵌套 JSON,如下所示?

{
"name":"myname",
"age":30,
"DOB":{
"day":20,
"month":"June",
"year":1988
}
}

最佳答案

@No-One,假设您已按如下方式定义模型。

http://www.django-rest-framework.org/api-guide/relations/

Use ForeignKey() for nested dictionary like {'day': 20, 'month': 'June', 'year': 1998}.

class Dob(models.Model):
day = models.IntegerField()
month = models.CharField(max_length=10)
year = models.IntegerField()

def __str__(self):
return str(self.day)

class User(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
age = models.IntegerField()
dob = models.ForeignKey(Dob, on_delete=models.CASCADE, null=False)

def __str__(self):
return self.name

enter image description here

enter image description here

然后我建议您像这样定义序列化器。

Please comment, if you've queries.

class DobSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Dob
fields = ('day', 'month', 'year')

class UserSerializer(serializers.HyperlinkedModelSerializer):
dob = DobSerializer(many=False, read_only=True);

class Meta:
model = User
fields = ('name', 'age', 'dob');

enter image description here

关于django - 使用 Django Rest Framework 将扁平 JSON 转换为嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780350/

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