Mercurial > public > sg101
comparison gpp/downloads/signals.py @ 203:40e5903903e1
Should have added signals.py in r203.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Wed, 28 Apr 2010 03:00:31 +0000 |
parents | |
children | 3a4bbf9c2cce |
comparison
equal
deleted
inserted
replaced
202:7aa061ed387c | 203:40e5903903e1 |
---|---|
1 """Signals for the downloads application. | |
2 We use signals to compute the denormalized category counts whenever a download | |
3 is saved.""" | |
4 from django.db.models.signals import post_save | |
5 from django.db.models.signals import post_delete | |
6 | |
7 from downloads.models import Category, Download | |
8 | |
9 | |
10 def on_download_save(sender, **kwargs): | |
11 """This function updates the count field for all categories. | |
12 It is called whenever a download is saved via a signal. | |
13 """ | |
14 if kwargs['created']: | |
15 # we only have to update the parent category | |
16 download = kwargs['instance'] | |
17 cat = download.category | |
18 cat.count = Download.public_objects.filter(category=cat).count() | |
19 cat.save() | |
20 else: | |
21 # update all categories just to be safe (an existing download could | |
22 # have been moved from one category to another | |
23 cats = Category.objects.all() | |
24 for cat in cats: | |
25 cat.count = Download.public_objects.filter(category=cat).count() | |
26 cat.save() | |
27 | |
28 | |
29 def on_download_delete(sender, **kwargs): | |
30 """This function updates the count field for the download's parent | |
31 category. It is called when a download is deleted via a signal. | |
32 """ | |
33 # update the parent category | |
34 download = kwargs['instance'] | |
35 cat = download.category | |
36 cat.count = Download.public_objects.filter(category=cat).count() | |
37 cat.save() | |
38 | |
39 | |
40 post_save.connect(on_download_save, sender=Download) | |
41 post_delete.connect(on_download_delete, sender=Download) |