Stop over-recursion in post contexts

This commit is contained in:
Andrew Godwin 2023-03-02 10:28:27 -07:00
parent 6411a375ba
commit 552a150e57
1 changed files with 5 additions and 2 deletions

View File

@ -105,6 +105,7 @@ class PostService:
# Retrieve descendants via breadth-first-search # Retrieve descendants via breadth-first-search
descendants: list[Post] = [] descendants: list[Post] = []
queue = [self.post] queue = [self.post]
seen: set[str] = set()
while queue and len(descendants) < num_descendants: while queue and len(descendants) < num_descendants:
node = queue.pop() node = queue.pop()
child_queryset = ( child_queryset = (
@ -119,8 +120,10 @@ class PostService:
else: else:
child_queryset = child_queryset.unlisted(include_replies=True) child_queryset = child_queryset.unlisted(include_replies=True)
for child in child_queryset: for child in child_queryset:
if child.pk not in seen:
descendants.append(child) descendants.append(child)
queue.append(child) queue.append(child)
seen.add(child.pk)
return ancestors, descendants return ancestors, descendants
def delete(self): def delete(self):