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')
|