1👍
You can try this:
from django.db.models import IntegerField, OuterRef, Subquery
class SQCount(Subquery):
output_field = IntegerField()
template = f"(SELECT count(*) from (%(subquery)s)) _count)"
subquery_count = SQCount(Subject.objects.filter(year_taken=OuterRef("year_taken")))
queryset = Subject.objects.annotate(count=subquery_count).order_by("year_taken").distinct("year_taken").values("year_taken", "count")
Source:stackexchange.com