(backend) list only the first visible parent document for a user

Now that we have a tree structure, we should only include parents of
a visible subtree in list results.
This commit is contained in:
Samuel Paccoud - DINUM
2024-12-17 07:35:09 +01:00
committed by Anthony LC
parent 9a12452c26
commit 48662ceecb
2 changed files with 57 additions and 6 deletions

View File

@@ -15,12 +15,14 @@ from django.db import models as db
from django.db.models import (
Count,
Exists,
F,
OuterRef,
Q,
Subquery,
Value,
)
from django.db.models.expressions import RawSQL
from django.db.models.functions import Left, Length
from django.http import Http404
import rest_framework as drf
@@ -395,6 +397,24 @@ class DocumentViewSet(
& ~db.Q(link_reach=models.LinkReachChoices.RESTRICTED)
)
)
# Among the results, we may have documents that are ancestors/children of each other
# In this case we want to keep only the highest ancestor. Let's annotate, each document
# with the path of its highest ancestor within results so we can use it to filter
shortest_path = Subquery(
queryset.filter(path=Left(OuterRef("path"), Length("path")))
.order_by("path") # Get the shortest (root) path
.values("path")[:1]
)
queryset = queryset.annotate(root_path=shortest_path)
# Filter documents based on their shortest path (root path)
queryset = queryset.filter(
root_path=F(
"path"
) # Keep only documents who are the annotated highest ancestor
)
else:
queryset = queryset.none()