diff --git a/atlas/views.py b/atlas/views.py index 48e7926c..740fd600 100755 --- a/atlas/views.py +++ b/atlas/views.py @@ -1229,7 +1229,17 @@ def case_search(request): # Exclude recent cases from the main search results to avoid duplication recent_pks = [c.pk for c in recent_cases] - cases = qs.exclude(pk__in=recent_pks).order_by("title")[:30] + + # Build the base queryset for results, apply excludes first (before slicing) + cases_qs = qs.exclude(pk__in=recent_pks) + + # Also exclude any cases that are already present in the collection + if collection is not None: + existing_pks = list(collection.cases.values_list("pk", flat=True)) + if existing_pks: + cases_qs = cases_qs.exclude(pk__in=existing_pks) + + cases = cases_qs.order_by("title")[:30] return render( request,