I have a Django model and I want to show some statistics about it. E.g. I have a field like color in it and I want to display how many of the entries have their color set to “red”, “green” etc.
Since I have a lot of rows in the table and several colors I do not want to calculate the sum of each statistic on every read.
Therefore I tried to come up with a second table holding the calculated sum. But now I have to keep this information in sync with the original table. E.g. whenever an entry is added, deleted or modifed, I have to update the statistic table.
How would I do something like this?
Depending of your row count but
select count(id) ... GROUP BYis generally fast.Otherwise, Django signals is a very interesting concept for this purpose. You can ‘listen’ to some events like model saved/deleted… or use your custom signals.
In your case, you want to listen to model
post_saveandpost_deletesignals.heres an example :
Place this code inside a models.py
Hope this helps.
EDIT : Also see this new F operator technique example for a single sql operation