Django,MySQL,JSONField -JSON数据的过滤问题

xcitsw88  于 11个月前  发布在  Mysql
关注(0)|答案(1)|浏览(90)

我在过滤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进行过滤,例如在内容、正文或页脚字段中。
错误消息:
我没有收到任何错误消息,但过滤不按预期工作。

f45qwnt8

f45qwnt81#

使用contains/icontains来过滤JSONField的值并不会给予你想要的结果。为了达到你想要的结果,你可以使用SubstrKT(Django >= 4. 2)

from django.db.models import CharField, Q
from django.db.models.functions import Substr

ChatMessage.objects.annotate(
    header_content=Substr("template_message__header__content", 1, output_field=CharField()),
    body=Substr("template_message__body", 1, output_field=CharField()),
    footer=Substr("template_message__footer", 1, output_field=CharField()),
).filter(
    Q(header_content__icontains=search_key)
    | Q(body__icontains=search_key)
    | Q(footer__icontains=search_key)
)

字符串
如果你使用的是Django >= 4.2,你可以使用KT如下

from django.db.models.fields.json import KT
from django.db.models import Q

ChatMessage.objects.annotate(
    header_content=KT("template_message__header__content"),
    body=KT("template_message__body"),
    footer=KT("template_message__footer"),
).filter(
    Q(header_content__icontains=search_key)
    | Q(body__icontains=search_key)
    | Q(footer__icontains=search_key)
)

相关问题