繁体   English   中英

如何处理来自外部 API 的 django 中的 json 响应

[英]How to deal with json response in django from external API

我目前正在使用来自外部 API(如 Amazon SP-API)的数据在 Django 中构建一个简单的仪表板。 我想知道如何将数据保存在数据库中,并在发生更改时让 django 更新字段。 我正在使用不同的刷新令牌迭代 100 多个帐户并获取客户订单并推送到数据库中。

我现在的model是:

class VendorOrder(models.Model):
    id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    purchase_order_number = models.CharField(max_length = 30)
    purchase_order_state = models.CharField(max_length = 30, default = "", null = True, blank = True)
    purchase_order_date = models.DateTimeField()
    last_updated_date = models.DateTimeField(null = True, blank = True)
    window_start = models.DateTimeField()
    window_end = models.DateTimeField()
    selling_party = models.CharField(max_length = 100)   
    warehouse = models.CharField(max_length = 100)
    item_sequence_number = models.IntegerField(null = True, blank = True)
    buyer_product_identifier = models.CharField(max_length = 30, default ="", null = True, blank = True)
    vendor_product_identifier = models.CharField(max_length = 30, default ="", null = True, blank = True)
    ordered_quantity = models.DecimalField(max_digits=20, decimal_places=2, null = True, blank = True)
    accepted_quantity = models.DecimalField(max_digits=20, decimal_places=2, null = True, blank = True)
    received_quantity = models.DecimalField(max_digits=20, decimal_places=2, null = True, blank = True)
    net_cost = models.DecimalField(max_digits=20, decimal_places=2, null = True, blank = True)
    net_cost_currency = models.CharField(max_length = 10, default ="", null = True, blank = True)
    total_cost = models.DecimalField(max_digits=20, decimal_places=2, null = True, blank = True)

目前我正在运行一个向 Amazon API 发出请求的 cronjob,我正在使用 update_or_create django function 将行保存在数据库中。

VendorOrder.update_or_create() 

有两件事想请教:

  1. 我正在使用两个不同的端点来获取 window_start 和 window_end 日期(没有包含项目和 window 日期的端点),我将它合并到一个字典中,然后保存到数据库。 我应该创建另一个带有日期的 model 并使用 purchase_order_number 作为外键吗?
  2. 我应该对物品做同样的事情吗? 如何使它们保持最新状态,因为 accepted_quantity 会随时间变化。 (现在我正在使用具有指定更改日期的端点,因此当采购订单更改时我会得到更新)。 我还创建了 unique_constraint 来跟踪更新,但我想知道我是否应该将整个采购订单保留为 JSON 字段并在需要时更新它。

谢谢

来自外部 API 数据的响应很可能包含在响应body中。 所以

body = request.body.decode("utf-8")

现在它将是字符串格式,你必须将它转换成可用的格式,所以,

import json
body = json.loads(body_unicode)

现在它将是dict或“列表”类型。 现在您可以轻松使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM