Skip to main content
 首页 » 编程设计

python之这个 SQL 语句有 django ORM 版本吗

2024年10月24日32虾米姐

使用 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 之间的冲突,尽管我对此表示怀疑?

请您参考如下方法:

https://docs.djangoproject.com/es/1.9/ref/contrib/postgres/fields/

你会做这样的事情:

WebFile.objects.filter(json_field__title__contains='moon')