I have a tree structure in postgres and I want to get the number of nested nodes for each visible node counting all children except the hidden child and its descendants. You can look at the SQL query to get an idea. I am trying to implement following query in 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;
What I am trying:
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())
)
I am getting an error coming from Django
as:
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
I can't figure out whether the error is coming from first annotate or the second one and how to fix it. I am using nested Subquery
as inner most select refers to the outermost path
column. The custom lookups are just for the postgres's <@
operator.
Thanks in advance for your help.