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