0

I want to get the count of records over 14 days

I'm currently doing:

class Invitation(models.Model):
    ...
    start_date = models.DateTimeField(default=timezone.now)

all_invitations = Invitation.objects.all()

days14 = all_invitations.filter(start_date__range=[today - timedelta(days=7), today + timedelta(days=8)]).annotate(day=TruncDay('start_date')).values('day').annotate(count=Count('id')).values('day', 'count').order_by('day')

However, this does not give me the days for which there are 0 invitations. How do I achieve that?

blue_zinc
  • 2,410
  • 4
  • 30
  • 38

1 Answers1

0

However, this does not give me the days for which there are 0 invitations.

You have already grouped on day before calculating the count

....values('day').annotate(count=Count('id'))

So these days will only be the ones which are present in the table and hence it doesn't include the days with 0 invitations.

I am not sure if this can fully be achieved through a query because the days you want are not present in the table. You could however do following:

  • get all the days in 14 days range in a set (s1)
  • get the days which are present in table within that 14 days range in another set (s2)
  • take the set difference of s1 and s2.
AKS
  • 18,983
  • 3
  • 43
  • 54