view gpp/weblinks/signals.py @ 260:3a4bbf9c2cce

Fixing #107. Apparently some signal handlers were getting connected twice (double import?) and thus saving a forum post would cause 2 email notifications to go out to the post topic's subscribers. Use the dispatch_uid parameter in the connect call to work around this issue.
author Brian Neal <bgneal@gmail.com>
date Wed, 22 Sep 2010 00:24:59 +0000
parents 7aa061ed387c
children
line wrap: on
line source
"""Signals for the weblinks application.
We use signals to compute the denormalized category counts whenever a weblink
is saved."""
from django.db.models.signals import post_save
from django.db.models.signals import post_delete

from weblinks.models import Category, Link


def on_link_save(sender, **kwargs):
    """This function updates the count field for all categories.
    It is called whenever a link is saved via a signal.
    """
    if kwargs['created']:
        # we only have to update the parent category
        link = kwargs['instance']
        cat = link.category
        cat.count = Link.public_objects.filter(category=cat).count()
        cat.save()
    else:
        # update all categories just to be safe (an existing link could
        # have been moved from one category to another
        cats = Category.objects.all()
        for cat in cats:
            cat.count = Link.public_objects.filter(category=cat).count()
            cat.save()


def on_link_delete(sender, **kwargs):
    """This function updates the count field for the link's parent
    category. It is called when a link is deleted via a signal.
    """
    # update the parent category
    link = kwargs['instance']
    cat = link.category
    cat.count = Link.public_objects.filter(category=cat).count()
    cat.save()


post_save.connect(on_link_save, sender=Link, dispatch_uid='weblinks.signals')
post_delete.connect(on_link_delete, sender=Link, dispatch_uid='weblinks.signals')