'Count different values of user over a period of time with selecting the latest for that day

I was trying to get models value over a period of time in django. The model is used to keep kind of activity log.

class Activity(models.Model):
    PLACE_CHOICES = (('home', 'Home'),('office', 'Office'))
    userId = models.IntegerField()
    date = models.DateField()
    place = models.CharField(max_length=25, choices=PLACE_CHOICES)

An user can have multiple place for a day ('place' can be duplicate) but I need only the latest model for that day.

I need to group data over a period of time (say 15 days) for multiple user, filtering args are something like this,

Activity.objects.filter(userId__in=[1,2], date__gte='2022-01-01', date__lte='2022-01-15')

This is only to show the filtering. I tried other methods,like-

Activity.objects.filter(
        userId__in=[1,2], date__gte='2022-01-01', date__lte='2022-01-15'
        ).annotate(
            home=Count('place', distinct=True, filter=Q(place='home'),
            office=Count('place', distinct=True, filter=Q(place='home')
        ).values('userId','home','office')

I need values like this

[{userId:1, home:4, office:3},{userId:2, home:1, office:3}]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source