我在过滤Django JSONField中存储的JSON数据时遇到了一个问题。当尝试使用icontains查找过滤数据时,它似乎将JSON数据视为字符串字段,并且过滤无法按预期工作。下面是我的设置的简要概述:
产品型号:
我有一个Django模型,JSONField是这样的:
from django.db import models
class ChatMessage(models.Model):
template_message = models.JSONField(null=True)
字符串
JSON数据以以下格式存储在数据库中:
{
"header": {
"type": "text",
"content": "Hello"
},
"body": "Hi there",
"footer": "Hello there"
}
型
问题描述:
我面临的问题是过滤代码。我想根据JSON数据中的值过滤对象,但icontains查找似乎将其视为字符串字段而不是JSON字段。
ChatMessage.objects.filter(
Q(template_message__header__content__icontains=search_key) |
Q(template_message__body__icontains=search_key) |
Q(template_message__footer__icontains=search_key)
)
型
预期结果:
我希望过滤考虑JSON结构,并根据任何JSON值中是否存在search_key
进行过滤,例如在内容、正文或页脚字段中。
错误消息:
我没有收到任何错误消息,但过滤不按预期工作。
1条答案
按热度按时间f45qwnt81#
使用
contains
/icontains
来过滤JSONField
的值并不会给予你想要的结果。为了达到你想要的结果,你可以使用Substr
或KT
(Django >= 4. 2)字符串
如果你使用的是Django >= 4.2,你可以使用
KT
如下型