如何在Django中将JSON数据插入数据库?

2024-06-16 12:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经建立了一个刮板,从不同的购物网站获取产品数据。在

当我运行python scraper.py时,程序将打印一个JSON对象,其中包含如下所有数据:

{   'ebay': [   {   'advertiser': 'ebay',
                    'advertiser_url': 'https://rover.ebay.com/rover/1/711-53200-19255-0/1?ff3=2&toolid=10041&campid=5338482617&customid=&lgeo=1&vectorid=229466&item=302847614914',
                    'description': '30-Day Warranty - Free Charger & Cable - '
                                   'Easy Returns!',
                    'main_image': 'https://thumbs1.ebaystatic.com/pict/04040_0.jpg',
                    'price': '290.0',
                    'title': 'Apple iPhone 8 Plus Smartphone AT&T Sprint '
                             'T-Mobile Verizon or Unlocked 4G LTE'}
                ]}

我希望每次运行scraper时,这些数据都会自动添加到数据库中。在

以下是我的数据库结构:

模型.py

^{pr2}$

Tags: 数据pyhttps程序刮板com数据库json
2条回答

将此添加到scrapper.py

import path.to.model

product = Product()
product.<key> = <value> #Where key is the field and value is the value you need to fill

在指定每个字段之后,添加 product.save()

如果json响应中的所有键都与模型中的字段匹配,则可以执行以下操作:

^{pr2}$

这将为您节省大量的线路和时间:)

我经常使用json;我有API缓存,可以接收大量基于json的API数据,并希望将其存储在数据库中以进行查询和缓存。如果使用postgres(例如),您将看到If有json的扩展。这意味着您可以将json数据保存在一个特殊的json字段中。但是更好的是,有一些sql扩展允许您对json数据运行查询。也就是说,postgres具有“无sql”功能。json允许您以本机方式使用json。我觉得它很有吸引力,我强烈推荐它。这是一个学习曲线,因为它使用了非传统的sql,但是见鬼,我们有stackoverflow。在

参见:https://django-postgres-extensions.readthedocs.io/en/latest/json.html

下面是一个小例子:

 product_onhand_rows = DearCache.objects.filter(
                object_type=DearObjectType.PRODUCT_AVAILABILITY.value).filter(
                dear_account_id=self.dear_api.account_id).filter(jdata__Location=warehouse).filter(jdata__SKU=sku).all()

在本例中,json存储在jdata字段中。 jdata_yulocation访问json中的键位置。 它筑巢等等。对于高级查询,我使用sql

^{pr2}$

此外,您还可以“展开”列表(这是一个复杂的示例,我的json有发票列表,每个列表都有一个行列表…)

/* 1. listing invoice lines. We have to iterate over the array of invoices to get each invoice, and then inside the invoice object find the array of lines */
select object_type,last_modified, jsonb_array_elements(jsonb_array_elements(cached_dear_dearcache.jdata#>'{Invoices}')->'Lines') as lines,
   jsonb_array_elements(cached_dear_dearcache.jdata#>'{Invoices}')->'InvoiceDate' as invoice_date,
   jsonb_array_elements(cached_dear_dearcache.jdata#>'{Invoices}')->'InvoiceNumber' as invoice_number
from cached_dear_dearcache
 where object_type = 'orders' order by last_modified;

您的方法是将json数据转换为传统的sql模型。那也行。不是很灵活。。。如果json“schema”发生更改,则可能需要更改数据库模式。从哲学上讲,我认为最好遵循流程,并使用json扩展,这是两个世界中最好的。顺便说一下,性能不错。在

相关问题 更多 >