fuxen_p
fuxen_p

Reputation: 55

Get time based model statistics in django

I know this is not a django question per say but I am working with django models and would like to have a solution specific to django

Suppose I have a model like this

class Foo(models.Model):
     type = models.IntegerField()
     timestamp = models.DateTimeField(auto_now_add=True)

Now what is the best method get a count of all objects of type(say 1) spread over date/time
For example: get_stat(type=1) gives me information on how many objects(of type 1) were created on 12/10/2018, on 13/10/2018, 14/10/2018 and so on...

Upvotes: 1

Views: 319

Answers (1)

Jrog
Jrog

Reputation: 1527

I think you need to use group by. See this answer: How to query as GROUP BY in django?

@classmethod
def get_stat(cls, type):
    return cls.objects.filter(type=type).values('timestamp').annotate(
        count=Count('id')
    ).values('timestamp', 'count')

This function is an example in your case.

Upvotes: 3

Related Questions