<p>我经常使用json;我有API缓存,可以接收大量基于json的API数据,并希望将其存储在数据库中以进行查询和缓存。如果使用postgres(例如),您将看到If有json的扩展。这意味着您可以将json数据保存在一个特殊的json字段中。但是更好的是,有一些sql扩展允许您对json数据运行查询。也就是说,postgres具有“无sql”功能。json允许您以本机方式使用json。我觉得它很有吸引力,我强烈推荐它。这是一个学习曲线,因为它使用了非传统的sql,但是见鬼,我们有stackoverflow。在</p>
<p>参见:<a href="https://django-postgres-extensions.readthedocs.io/en/latest/json.html" rel="nofollow noreferrer">https://django-postgres-extensions.readthedocs.io/en/latest/json.html</a></p>
<p>下面是一个小例子:</p>
<pre><code> 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()
</code></pre>
<p>在本例中,json存储在jdata字段中。
jdata_yulocation访问json中的键位置。
它筑巢等等。对于高级查询,我使用sql</p>
^{pr2}$
<p>此外,您还可以“展开”列表(这是一个复杂的示例,我的json有发票列表,每个列表都有一个行列表…)</p>
<pre><code>/* 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;
</code></pre>
<p>您的方法是将json数据转换为传统的sql模型。那也行。不是很灵活。。。如果json“schema”发生更改,则可能需要更改数据库模式。从哲学上讲,我认为最好遵循流程,并使用json扩展,这是两个世界中最好的。顺便说一下,性能不错。在</p>