Mercurial > public > sg101
comparison downloads/signals.py @ 581:ee87ea74d46b
For Django 1.4, rearranged project structure for new manage.py.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 05 May 2012 17:10:48 -0500 |
parents | gpp/downloads/signals.py@3a4bbf9c2cce |
children | 929d0e637a37 |
comparison
equal
deleted
inserted
replaced
580:c525f3e0b5d0 | 581:ee87ea74d46b |
---|---|
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 dispatch_uid='downloads.signals') | |
42 post_delete.connect(on_download_delete, sender=Download, | |
43 dispatch_uid='downloads.signals') |