[Django]-Django – Annotate Count() of distinct values grouped by Date

3👍

You can make a query like:

from django.db.models import Count
from django.db.models.functions import TruncDate

Visualization.objects.values(
    date=TruncDate('start_time')
).annotate(
    total=Count('user', distinct=True)
).order_by('date')

For days where no reproduction is made, there will not be row in the QuerySet, so you will need to post-process these dates.

0👍

You can use extra() QuerySet modifier for group by date query:

from django.db.models import Count

Visualization.objects.extra(
    select={'start_date': 'date( start_time )'}
).values(
    'start_date'
).annotate(
    total=Count('user', distinct=True)
)

Leave a comment