I have a model:
class Event(models.Model):
start_date = DateTimeField()
end_date = DateTimeField()
I want to count all events which are of the same day and include this count as annotation field daily_events
to the each member of queryset. I want to solve this on database side for speed. My code so far:
from django.db.models import F, Q, DateTimeField, Count
from django.db.models.functions import TruncDate
events = Event.objects.all()
events = events.annotate(
daily_events=Count('pk', filter=Q(start_date__date=TruncDate(F('start_date')))))
for event in events:
print(event.daily_events)
For example I have 4 events, and first 3 at the same day, so desired output should be:
3
3
3
1
but current output is wrong:
1
1
1
1
Any advices?