comparison weblinks/receivers.py @ 921:6d08b1476a52

Weblinks app refactor. For Django 1.7.7 upgrade.
author Brian Neal <bgneal@gmail.com>
date Tue, 07 Apr 2015 20:16:06 -0500
parents weblinks/signals.py@ee87ea74d46b
children
comparison
equal deleted inserted replaced
920:5902dc5e58a3 921:6d08b1476a52
1 """Signal handlers for the weblinks application.
2
3 We use signals to compute the denormalized category counts whenever a weblink
4 is saved.
5 """
6 from django.db.models.signals import post_save
7 from django.db.models.signals import post_delete
8
9 from weblinks.models import Category, Link
10
11
12 def on_link_save(sender, **kwargs):
13 """This function updates the count field for all categories.
14 It is called whenever a link is saved via a signal.
15 """
16 if kwargs['created']:
17 # we only have to update the parent category
18 link = kwargs['instance']
19 cat = link.category
20 cat.count = Link.public_objects.filter(category=cat).count()
21 cat.save()
22 else:
23 # update all categories just to be safe (an existing link could
24 # have been moved from one category to another
25 cats = Category.objects.all()
26 for cat in cats:
27 cat.count = Link.public_objects.filter(category=cat).count()
28 cat.save()
29
30
31 def on_link_delete(sender, **kwargs):
32 """This function updates the count field for the link's parent
33 category. It is called when a link is deleted via a signal.
34 """
35 # update the parent category
36 link = kwargs['instance']
37 cat = link.category
38 cat.count = Link.public_objects.filter(category=cat).count()
39 cat.save()
40
41
42 post_save.connect(on_link_save, sender=Link, dispatch_uid='weblinks.receivers')
43 post_delete.connect(on_link_delete, sender=Link, dispatch_uid='weblinks.receivers')