bgneal@202: """Signals for the weblinks application. bgneal@202: We use signals to compute the denormalized category counts whenever a weblink bgneal@202: is saved.""" bgneal@202: from django.db.models.signals import post_save bgneal@202: from django.db.models.signals import post_delete bgneal@202: bgneal@202: from weblinks.models import Category, Link bgneal@202: bgneal@202: bgneal@202: def on_link_save(sender, **kwargs): bgneal@202: """This function updates the count field for all categories. bgneal@202: It is called whenever a link is saved via a signal. bgneal@202: """ bgneal@202: if kwargs['created']: bgneal@202: # we only have to update the parent category bgneal@202: link = kwargs['instance'] bgneal@202: cat = link.category bgneal@202: cat.count = Link.public_objects.filter(category=cat).count() bgneal@202: cat.save() bgneal@202: else: bgneal@202: # update all categories just to be safe (an existing link could bgneal@202: # have been moved from one category to another bgneal@202: cats = Category.objects.all() bgneal@202: for cat in cats: bgneal@202: cat.count = Link.public_objects.filter(category=cat).count() bgneal@202: cat.save() bgneal@202: bgneal@202: bgneal@202: def on_link_delete(sender, **kwargs): bgneal@202: """This function updates the count field for the link's parent bgneal@202: category. It is called when a link is deleted via a signal. bgneal@202: """ bgneal@202: # update the parent category bgneal@202: link = kwargs['instance'] bgneal@202: cat = link.category bgneal@202: cat.count = Link.public_objects.filter(category=cat).count() bgneal@202: cat.save() bgneal@202: bgneal@202: bgneal@202: post_save.connect(on_link_save, sender=Link) bgneal@202: post_delete.connect(on_link_delete, sender=Link)