Django QuerySet:无法解析表达式类型,output_field未知

时间:2019-04-08 22:39:52

标签: django django-rest-framework django-queryset postgresql-9.5 django-1.11

我在postgres中有一个树结构,我想获取每个可见节点的嵌套节点数,该节点数除了隐藏子项及其后代之外的所有子项。您可以看一下SQL查询来了解一下。 我正在尝试在Django 1.11.20中实现以下查询:

select 
id, 
path, 
(
    select count(*)
    from tree_node
    where 
        path <@ t.path and 
        not path <@ array(
            select path
            from tree_node
            where path <@ t.path and visibility_id = 0
        )
) as nested_nodes
from tree_node t;

我正在尝试:

TreeQuerySet.py

...

def annotate_visibile_nested_nodes_count(self):
    """
    Get all nested nodes for current path except the hidden ones and their descendants
    """
    from src.tree.models import Visibility
    invisible_nested_nodes_paths = self.model.objects.filter(path__descendantsof=OuterRef(OuterRef('path')))\
                                                     .filter(visibility_id=Visibility.HIDE)\
                                                     .values('path')
    visible_nested_nodes_count = self.model.objects.filter(path__descendantsof=OuterRef('path'))\
                                                    .exclude(path__descendantsin=Subquery(invisible_nested_nodes_paths))\
                                                    .annotate(count=Count('*'))\
                                                    .values('count')[:1]

    return self.annotate(
        nested_nodes=Subquery(visible_nested_nodes_count, output_field=IntegerField())
    )

我收到来自Django的错误消息:

File ".../django/db/models/expressions.py", line 237, in output_field
raise FieldError("Cannot resolve expression type, unknown output_field")
FieldError: Cannot resolve expression type, unknown output_field

我无法弄清楚错误是来自第一个注释还是第二个注释以及如何解决。我将嵌套Subquery用作最里面的选择,引用最外面的path列。自定义查找仅适用于Postgres的<@运算符。

预先感谢您的帮助。

0 个答案:

没有答案