首页 > 解决方案 > 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[]

标签: pythondjangopostgresql

解决方案


这可能是因为 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)

推荐阅读