django-gcharts icon indicating copy to clipboard operation
django-gcharts copied to clipboard

Counting rows over time

Open jonashaag opened this issue 11 years ago • 3 comments

I need a graph that shows the number of objects over time. The objects have a date(time) field.

Unfortunately, there's no uniform way of annotating rows with their row number in Django/SQL.

Idea: Provide some way to plug in a transformation on the rows/queryset fetched from the database. For example

Thing.gcharts.to_json(
    labels={'date': "Date", 'number_of_things': {'number': "Number of things that exist"}},
    map=annotate_with_number,
    ...
)

def annotate_with_number(queryset):
    for row_number, row in enumerate(queryset):
        row.number_of_things = row_number
        yield row

jonashaag avatar Jan 15 '14 21:01 jonashaag

I'm not quite sure I understand what you want to do. By row number you mean id/primary key?

Generally speaking, you can get the number of items in a queryset with MyModel.objects.count().

rhblind avatar Jan 15 '14 22:01 rhblind

I want to plot the number of instances in the database over time. Now in my case the number of objects can only increase, never decrease, so an easy way to transform the query into something Google Charts can understand is to just annotate each row with its index in the queryset and order things by date.

Say we have a LogEntry object that has a timestamp. Now I want to plot the number of log entries in the databaase over time. I can do that by using the timestamp as X and the number of entries in the DB at that point in time as Y value - which is, in this case, the index of that entry in the queryset.

------+------+-----------+-------------
rowno |  id  | timestamp | log content
------+------+-----------+-------------
    1 |   42 | 2013/12/5 | Some text
    2 |  108 | 2013/12/6 | Some text
    3 | 5387 | 2013/12/9 | Some text

Number of entries in DB at 2013/12/5: 1 Number of entries in DB at 2013/12/6: 2 Number of entries in DB at 2013/12/9: 3

http://www.openwinforms.com/row_number_to_sql_select.html

jonashaag avatar Jan 15 '14 23:01 jonashaag

Aha, right! Well, that sounds like a good idea =) I like the idea of having map kwarg which takes a function argument and yields the results. It should be implemented as a general purpose function though.

If you have a good idea implementation-wise, please share your thoughts (or submit a pull request ;)). I'm a little busy at work these days so I don't have time to look into it now, but I like the idea.

Cheers!

rhblind avatar Jan 16 '14 08:01 rhblind