Fabian
Fabian

Reputation: 5650

Django keep statistics up to date

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?

Upvotes: 1

Views: 596

Answers (2)

jujule
jujule

Reputation: 11521

Depending of your row count but select count(id) ... GROUP BY is 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_save and post_delete signals.

heres an example :

from django.db.models import signals
import models

def itemSaved(sender, **kwargs):
    obj = kwargs['instance']
    colorMod =  models.Color.get(name = obj.color)
    colorMod.count = colorMod.count + 1
    colorMod.save()

# listen to post_save event for model MyModel
signals.post_save.connect(itemSaved, sender=models.MyModel)

Place this code inside a models.py

Hope this helps.

EDIT : Also see this new F operator technique example for a single sql operation

Upvotes: 3

Bjorn
Bjorn

Reputation: 5362

You can use Django Signals for this. Specifically, look at post_save and post_delete. http://docs.djangoproject.com/en/dev/ref/signals/

Upvotes: 1

Related Questions