【发布时间】:2016-04-15 16:02:09
【问题描述】:
使用 Django 1.9 和 Postgres 9.4。
我有一个名为 json_field 的 jsonb 字段。 json_field 可以包含密钥 title,它可能看起来像 'the cow jumped over the moon'。
所以我想搜索title 包含moon 的行。
使用以下原始 SQL 可以正常工作
SELECT * FROM web_file where (json_field ->> 'title')::text LIKE '%moon%';
但我宁愿使用 Django ORM。
编辑:
我想尝试一下(正如@kloddant 所指出的那样)
title = WebFile.objects.filter(json_field__title__contains='moon')
但它给出了以下错误
DataError: invalid input syntax for type json
LINE 1: ...le" WHERE "web_file"."json_field" -> 'title' @> 'moon' ORD...
^
DETAIL: Token "moon" is invalid.
CONTEXT: JSON data, line 1: moon
这里是相关的models.py
from django.contrib.postgres.fields import JSONField
class WebFile(MPTTModel):
json_field = JSONField(null=True, blank=True, default=dict())
这可能是 django 模型和 MPTTModel 之间的冲突,尽管我对此表示怀疑?
【问题讨论】:
-
JSONField 字段类型从何而来?它不是 Django 的一部分,也不是 MPTT 的一部分。
-
@MadWombat 它在 Django 1.9 中的新功能docs.djangoproject.com/es/1.9/ref/contrib/postgres/fields/…
-
您可能想阅读文档。 JSONField 不是字符串,因此看起来
__contains过滤器可能与字符串不同。 docs.djangoproject.com/es/1.9/ref/contrib/postgres/fields/… -
阅读更多,看起来你需要将字典传递给__contains
标签: python django django-orm postgresql-9.4 postgresql-json