Mercurial > public > sg101
comparison weblinks/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/weblinks/signals.py@3a4bbf9c2cce |
children |
comparison
equal
deleted
inserted
replaced
580:c525f3e0b5d0 | 581:ee87ea74d46b |
---|---|
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, dispatch_uid='weblinks.signals') | |
41 post_delete.connect(on_link_delete, sender=Link, dispatch_uid='weblinks.signals') |