【发布时间】:2021-11-10 16:43:20
【问题描述】:
我正在使用 Django 提供的 JSONField,并将此类数据存储在该字段中:
[
{
"number": 1,
"text": "This text is about dogs"
},
{
"number": 2,
"text": "Only cats in this text here"
},
{
"number": 3,
"text": "However, this text does also contain dogs"
},
]
我想要实现的是某种子字符串匹配 - 即,如果一个人搜索字符串 "dog",结果应该返回如下内容:
{
"number": 1,
"text": "This text is about dogs"
},
{
"number": 3,
"text": "However, this text does also contain dogs"
},
查看 Django 文档,似乎可以查询 JSON 字段,因此
Model.objects.filter(field__text__contains='dogs')
但是,contains 仅适用于单个字典值,不适用于存在字典数组时。
有什么建议吗?通过 Django ORM 或直接通过 Postgres。
【问题讨论】:
-
您可能会找到使用 JSONPATH 查询的解决方案,但效果不佳。使用规范化的数据模型而不是 JSON 数组,练习会变得简单,查询也会很快。
标签: django postgresql django-orm