python - Django CARDINALITY Query 不允许通过 equals 过滤,但适用于 < 或 >
问题描述
我有一个 Document 模型,其中包含一个 ArrayField 页面。我想找到所有零页文档的列表。
型号字段:
content = ArrayField(models.TextField(), default=list, blank=True)
我使用注释函数首先为页数创建一个计算字段,然后尝试过滤等于零的页数。这是我要运行的查询:
qs = Document.objects.all() \
.annotate(content_len=Func(F('content'), function='CARDINALITY')) \
.exclude(content_len=0) # this DOESN'T WORK
.exclude(content_len__lt=1) # this WORKS
不起作用的版本会生成以下 SQL 错误:
WHERE CARDINALITY("dockets_document"."content") = 0::text[]
>>> psycopg2.errors.CannotCoerce: cannot cast type integer to text[]
解决方案
这可能是因为 Django 无法推断字段的类型。您可以通过output_field
参数指定它来给它一个“提示”:
from django.db.models import IntegerField
qs = Document.objects.annotate(
content_len=Func(F('content'), function='CARDINALITY', output_field=IntegerField())
).exclude(content_len=0)
推荐阅读
- spring - 在 Spring 项目(不是 Spring Boot)上配置 Open API 3
- python - 表单返回的用户名值无效
- python - PlotnineError: 'Aesthetics must either be length one, or the same length as the data'
- powershell - 用点替换数组中的所有逗号
- .net - 在 Linux 中共享 .NET 应用程序的 DLL
- ruby - 替换特定路径中的字符串 url
- reactjs - ant设计框架中如何在表单外调用onFinish方法
- azure-devops - 使用 Power Automate 将父字段从 DevOps 导出到 Sharepoint 列表
- excel - 等待一段时间而不暂停工作表
- python - 删除时间间隔在一小时内的相似记录