Repository: wagtail/wagtail
File: wagtail/documents/views/documents.py (Python)

Code before:
    model = get_document_model()
    add_item_label = gettext_lazy("Add a document")
    show_other_searches = True

    def get_base_queryset(self):
        # Get documents (filtered by user permission and annotated with usage counts)
        documents = (
            self.permission_policy.instances_user_has_any_permission_for(
                self.request.user, ["change", "delete"]
            )
            .select_related("collection")
            .annotate(
                usage_count=Coalesce(
                    Subquery(
                        ReferenceIndex.objects.filter(
                            to_content_type=ContentType.objects.get_for_model(Document),
                            to_object_id=Cast(OuterRef("pk"), output_field=CharField()),
                        )
                        .values("object_id", "to_object_id")
                        .distinct()
                        .values("to_object_id")
                        .annotate(count=Count("object_id", distinct=True))
                        .values("count")
                    ),
                    0,
                )
            )
        )

        return documents

    @cached_property
    def current_collection(self):
        # Upon validation, the cleaned data is a Collection instance
        return self.filters and self.filters.form.cleaned_data.get("collection_id")

    @cached_property
    def columns(self):
        columns = [
            BulkActionsColumn("bulk_actions"),
            TitleColumn(
                "title",
                label=_("Title"),
                sort_key="title",
                get_url=self.get_edit_url,
                get_title_id=lambda doc: f"document_{quote(doc.pk)}_title",
            ),
            DownloadColumn("filename", label=_("File")),
            DateColumn(
                "created_at",
                label=_("Created"),

Review comment (refactor):
Would be nice if we could extract this into a method on the `ReferenceIndex` e.g.

```py
@classmethod
def usage_count_subquery(cls, model):
    return Coalesce(
        Subquery(
            ReferenceIndex.objects.filter(
                to_content_type=ContentType.objects.get_for_model(model),
                to_object_id=Cast(OuterRef("pk"), output_field=CharField()),
            )
            .values("object_id", "to_object_id")
            .distinct()
            .values("to_object_id")
            .annotate(count=Count("object_id", distinct=True))
            .values("count")
        ),
        0,
    )
```

and then we can reuse this for both documents and images e.g.

```suggestion
                usage_count=ReferenceIndex.usage_count_subquery(Document)
```

Code after:
            self.request.user, ["change", "delete"]
        ).select_related("collection")

        # Annotate with usage count from the ReferenceIndex
        documents = documents.annotate(
            usage_count=ReferenceIndex.usage_count_subquery(self.model)
        )

        return documents

    @cached_property
    def current_collection(self):
        # Upon validation, the cleaned data is a Collection instance
        return self.filters and self.filters.form.cleaned_data.get("collection_id")

    @cached_property
    def columns(self):
        columns = [
            BulkActionsColumn("bulk_actions"),
            TitleColumn(
                "title",
                label=_("Title"),
                sort_key="title",
                get_url=self.get_edit_url,
                get_title_id=lambda doc: f"document_{quote(doc.pk)}_title",
            ),
            DownloadColumn("filename", label=_("File")),
            DateColumn(
                "created_at",
                label=_("Created"),
                sort_key="created_at",
            ),
            UsageCountColumn(
                "usage_count",
                label=_("Usage"),
                width="16%",
                sort_key="usage_count",
            ),
        ]
        if self.filters and "collection_id" in self.filters.filters:
            columns.insert(
                3,
                Column("collection", label=_("Collection"), accessor="collection.name"),
            )
        return columns

    @cached_property
    def collections(self):
        collections = permission_policy.collections_user_has_any_permission_for(
            self.request.user, ["add", "change"]
        )