I want to get count of a query set after selecting distinct of another field .
My code:
module_attempts_count = Subquery(ModuleProgressAttempt.objects.filter(
module_progress__module__id=OuterRef('id')).values('module_progress__user').distinct().values(
'module_progress__module__id').annotate(count=Count('id')).values('count'))
real_instances = VirtualClassRoomModule.objects.filter(
id__in=[vc.id for vc in vc_classrooms]).annotate(attendees_count=module_attempts_count,)
Im annotating a count field into the queryset . For evaluating the count i want the ModuleProgressAttempt of the current item with module_progress__user distinctly . One user should only be counted once . Postgres supports distinct('module_progress__user'). I want it to work in all databases. Current solution takes the total count without considering the distinct user .
This worked.
Subquery(ModuleProgressAttempt.objects.filter(
module_progress__module__id=OuterRef('id')).values('module_progress__module__id')
.annotate(count=Count('module_progress__user__id', distinct=True)).values('count'))