Mercurial > public > sg101
annotate gpp/downloads/signals.py @ 318:c550933ff5b6
Fix a bug where you'd get an error when trying to delete a forum thread (topic does not exist). Apparently when you call topic.delete() the posts would get deleted, but the signal handler for each one would run, and it would try to update the topic's post count or something, but the topic was gone? Reworked the code a bit and explicitly delete the posts first. I also added a sync() call on the parent forum since post counts were not getting adjusted.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 05 Feb 2011 21:46:52 +0000 |
parents | 3a4bbf9c2cce |
children |
rev | line source |
---|---|
bgneal@203 | 1 """Signals for the downloads application. |
bgneal@203 | 2 We use signals to compute the denormalized category counts whenever a download |
bgneal@203 | 3 is saved.""" |
bgneal@203 | 4 from django.db.models.signals import post_save |
bgneal@203 | 5 from django.db.models.signals import post_delete |
bgneal@203 | 6 |
bgneal@203 | 7 from downloads.models import Category, Download |
bgneal@203 | 8 |
bgneal@203 | 9 |
bgneal@203 | 10 def on_download_save(sender, **kwargs): |
bgneal@203 | 11 """This function updates the count field for all categories. |
bgneal@203 | 12 It is called whenever a download is saved via a signal. |
bgneal@203 | 13 """ |
bgneal@203 | 14 if kwargs['created']: |
bgneal@203 | 15 # we only have to update the parent category |
bgneal@203 | 16 download = kwargs['instance'] |
bgneal@203 | 17 cat = download.category |
bgneal@203 | 18 cat.count = Download.public_objects.filter(category=cat).count() |
bgneal@203 | 19 cat.save() |
bgneal@203 | 20 else: |
bgneal@203 | 21 # update all categories just to be safe (an existing download could |
bgneal@203 | 22 # have been moved from one category to another |
bgneal@203 | 23 cats = Category.objects.all() |
bgneal@203 | 24 for cat in cats: |
bgneal@203 | 25 cat.count = Download.public_objects.filter(category=cat).count() |
bgneal@203 | 26 cat.save() |
bgneal@203 | 27 |
bgneal@203 | 28 |
bgneal@203 | 29 def on_download_delete(sender, **kwargs): |
bgneal@203 | 30 """This function updates the count field for the download's parent |
bgneal@203 | 31 category. It is called when a download is deleted via a signal. |
bgneal@203 | 32 """ |
bgneal@203 | 33 # update the parent category |
bgneal@203 | 34 download = kwargs['instance'] |
bgneal@203 | 35 cat = download.category |
bgneal@203 | 36 cat.count = Download.public_objects.filter(category=cat).count() |
bgneal@203 | 37 cat.save() |
bgneal@203 | 38 |
bgneal@203 | 39 |
bgneal@260 | 40 post_save.connect(on_download_save, sender=Download, |
bgneal@260 | 41 dispatch_uid='downloads.signals') |
bgneal@260 | 42 post_delete.connect(on_download_delete, sender=Download, |
bgneal@260 | 43 dispatch_uid='downloads.signals') |