annotate downloads/signals.py @ 681:53a56d19568c

For Django 1.5.2; cleanup command is now called clearsessions.
author Brian Neal <bgneal@gmail.com>
date Fri, 16 Aug 2013 20:43:39 -0500
parents 929d0e637a37
children
rev   line source
bgneal@203 1 """Signals for the downloads application.
bgneal@203 2 We use signals to compute the denormalized category counts whenever a download
bgneal@203 3 is saved."""
bgneal@203 4 from django.db.models.signals import post_save
bgneal@203 5 from django.db.models.signals import post_delete
bgneal@203 6
bgneal@664 7 from downloads.models import Category, Download, PendingDownload
bgneal@203 8
bgneal@203 9
bgneal@203 10 def on_download_save(sender, **kwargs):
bgneal@203 11 """This function updates the count field for all categories.
bgneal@203 12 It is called whenever a download is saved via a signal.
bgneal@203 13 """
bgneal@203 14 if kwargs['created']:
bgneal@203 15 # we only have to update the parent category
bgneal@203 16 download = kwargs['instance']
bgneal@203 17 cat = download.category
bgneal@203 18 cat.count = Download.public_objects.filter(category=cat).count()
bgneal@203 19 cat.save()
bgneal@203 20 else:
bgneal@203 21 # update all categories just to be safe (an existing download could
bgneal@203 22 # have been moved from one category to another
bgneal@203 23 cats = Category.objects.all()
bgneal@203 24 for cat in cats:
bgneal@203 25 cat.count = Download.public_objects.filter(category=cat).count()
bgneal@203 26 cat.save()
bgneal@203 27
bgneal@203 28
bgneal@203 29 def on_download_delete(sender, **kwargs):
bgneal@203 30 """This function updates the count field for the download's parent
bgneal@203 31 category. It is called when a download is deleted via a signal.
bgneal@664 32
bgneal@664 33 We now delete the uploaded file when the download is deleted.
bgneal@203 34 """
bgneal@203 35 # update the parent category
bgneal@203 36 download = kwargs['instance']
bgneal@203 37 cat = download.category
bgneal@203 38 cat.count = Download.public_objects.filter(category=cat).count()
bgneal@203 39 cat.save()
bgneal@203 40
bgneal@664 41 # delete the actual file
bgneal@664 42 if download.file:
bgneal@664 43 download.file.delete(save=False)
bgneal@664 44
bgneal@664 45
bgneal@664 46 def on_pending_download_delete(sender, **kwargs):
bgneal@664 47 """Delete the uploaded file if it exists."""
bgneal@664 48
bgneal@664 49 download = kwargs['instance']
bgneal@664 50 # delete the actual file
bgneal@664 51 if download.file:
bgneal@664 52 download.file.delete(save=False)
bgneal@664 53
bgneal@203 54
bgneal@260 55 post_save.connect(on_download_save, sender=Download,
bgneal@260 56 dispatch_uid='downloads.signals')
bgneal@260 57 post_delete.connect(on_download_delete, sender=Download,
bgneal@260 58 dispatch_uid='downloads.signals')
bgneal@664 59 post_delete.connect(on_pending_download_delete, sender=PendingDownload,
bgneal@664 60 dispatch_uid='downloads.signals')