【问题标题】:How to save external API's data in a django model?如何将外部 API 的数据保存在 django 模型中?
【发布时间】:2019-10-12 05:29:23
【问题描述】:

我正在从外部 API 中提取一些 JSON 数据。

{
   "id": 1,
   "body": "example json"
},
{
   "id": 2,
   "body": "example json"
}

我的用户模型:

class User(models.Model):
      body = models.CharField(max_length=200)

如何将 json 响应保存到我的模型中?

【问题讨论】:

    标签: python json django rest api


    【解决方案1】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-13
      • 2013-11-29
      • 2023-03-29
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多