当我收到像
这样的JSON数据时[
{
"id":1,
"name":"New Island",
"residents":[
{
"name":"Paul",
"age":"25"
}
]
},
{
"id":2,
"name":"One Nation",
"residents":[
{
"name":"James",
"age":"23"
},
{
"name":"Jessica",
"age":"26"
}
]
}
]
drf deserializer使其列出包含OrderedDict
的列表但是我想把它变成类对象的列表。
这是我的django模型
class Country(models.Model):
name = models.CharField(max_length=20)
class Resident(models.Model):
name = models.CharField(max_length=20)
country = models.ForeignKey('Country', related_name='residents')
答案 0 :(得分:1)
来自Python的JSON library
import json
data = '[{"id":1,"name":"New Island","residents":[{"name":"Paul","age":"25"}]},{"id":2,"name":"One Nation","residents":[{"name":"James","age":"23"},{"name":"Jessica","age":"26"}]}]'
x = json.loads(data)
for each_set in x:
for every_person in each_set["residents"]:
print(every_person["name"]) #getting resident's name
print(every_person["age"]) #getting age
print(each_set["name"]) #getting the country name
从那里开始就像将适当的参数传递给像
这样的类一样简单答案 1 :(得分:0)