我正在从外部API中拉入一些JSON数据。
{
"id": 1,
"body": "example json"
},
{
"id": 2,
"body": "example json"
}
我的用户模型:
class User(models.Model):
body = models.CharField(max_length=200)
如何将json响应保存到我的模型中?
发布于 2019-05-26 10:22:17
使用Model API保存模型定义的对象
import json
json_result = '''{
"id": 2,
"body": "example json"
}'''
data = json.loads(json_result) # first convert to a dict
id = data.get("id") # get the id
body = data.get("body") # get the body
user = User.objects.create(id=id, body=body) # create a User object
user.save() # save it
https://stackoverflow.com/questions/56312501
复制相似问题