djangodjango-orm

Count unique values and group by date


I have a table like:

client_id action date (datetime)
1 visit 2024-10-10 10:00
1 visit 2024-10-10 12:00
1 visit 2024-10-10 13:00
2 visit 2024-10-10 13:00

So, I need to count amount of unique clients with group by date. The result should look like {'date': 2024-10-10, "count_visits": 2}.

I tried several variations with annotate(unique=True) and OuterRef, but it never worked to group by date.


Solution

  • For pure ORM solution you should be able to use this

    from django.db.models import Count
    from django.db.models.functions import TruncDate
    
    YourTable.objects.annotate(pure_date=TruncDate('your_date_field_name')).values('pure_date').annotate(count_visits=Count('client_id', distinct=True))