# HG changeset patch # User Brian Neal # Date 1272423631 0 # Node ID 40e5903903e164bcc44153c9a5b43a6297cfa459 # Parent 7aa061ed387c3feb4395e2c30d4d746fbff5b0ef Should have added signals.py in r203. diff -r 7aa061ed387c -r 40e5903903e1 gpp/downloads/signals.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/gpp/downloads/signals.py Wed Apr 28 03:00:31 2010 +0000 @@ -0,0 +1,41 @@ +"""Signals for the downloads application. +We use signals to compute the denormalized category counts whenever a download +is saved.""" +from django.db.models.signals import post_save +from django.db.models.signals import post_delete + +from downloads.models import Category, Download + + +def on_download_save(sender, **kwargs): + """This function updates the count field for all categories. + It is called whenever a download is saved via a signal. + """ + if kwargs['created']: + # we only have to update the parent category + download = kwargs['instance'] + cat = download.category + cat.count = Download.public_objects.filter(category=cat).count() + cat.save() + else: + # update all categories just to be safe (an existing download could + # have been moved from one category to another + cats = Category.objects.all() + for cat in cats: + cat.count = Download.public_objects.filter(category=cat).count() + cat.save() + + +def on_download_delete(sender, **kwargs): + """This function updates the count field for the download's parent + category. It is called when a download is deleted via a signal. + """ + # update the parent category + download = kwargs['instance'] + cat = download.category + cat.count = Download.public_objects.filter(category=cat).count() + cat.save() + + +post_save.connect(on_download_save, sender=Download) +post_delete.connect(on_download_delete, sender=Download)