在 Django 中从 json 提要创建模型

Create models from json feed in Django

我正在制作一个 django 应用程序来浏览不同市场的可用产品。我正在从 JSON url 提要中获取我的模型数据,我不确定将这些数据转化为模型的最佳方法,因为单个市场的提要可以包含超过 50k 个项目。

模型 - 欢迎提出任何改进建议

# Details of a sellable products
class Product(models.Model):
    item = models.IntegerField(primary_key=True, auto_created=False)
    name = models.CharField(max_length=40)

# Market where products can be bought, some markets will cater to multiple suburbs.
class Market(models.Model):
    id = models.IntegerField(primary_key=True, auto_created=True)
    name = models.CharField(max_length=40)

# Nearby suburbs can share the one market
class Suburb(models.Model):
    name = models.CharField(max_length=30)
    market = models.ForeignKey(Market, on_delete=models.SET_NULL, null=True)

# Actual product for sale
class ProductForSale(models.Model):
    sale = models.IntegerField(primary_key=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    cost = models.IntegerField(default=1)
    owner = models.CharField(max_length=30)
    quantity = models.IntegerField(default=1)
    market = models.ForeignKey(Market,on_delete=models.SET_NULL, null=True )

市场产品信息流示例

"market_products": [
    {
        "id":11654,
        "item":123,
        "owner":"Bob",
        "suburb":"Springvale",
        "cost":3,
        "quantity":1,

    },
    {
        "id":11655,
        "item":123,
        "owner":"Sarah",
        "suburb":"Sunnyville",
        "cost":5,
        "quantity":2,

    },

这就是我试图填充我的 ProductForSale 模型的方式 - 我不知道这是否是产品 FK 的正确方法,或者如何link 郊区到它的市场 FK

    markets = Market.objects.all()
    for market in markets:
        url = "jsonurl"
        response = urllib.request.urlopen(url)
        data = json.loads(response.read())
        for entry in data['market_products']:
                new_product_sale = ProductForSale.objects.create(
                    product = Product.objects.get(item=entry['item']),
                    cost = entry['cost'],
                    owner = entry['owner'],
                    quantity = entry['quantity']
                )
                new_product_sale.save()

我是否应该为每个市场产品创建一个单独的模型,或者将它们全部放在一个模型中好吗?

最终为所有市场产品采用一种模型,到目前为止还没有遇到任何问题。