from django.db import transaction from django.db.models import Sum from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from .models import Subscription, UsageRecord from .usage_accounting import lock_usage_subscriptions def recompute_subscription_usage(subscription_id): with transaction.atomic(): lock_usage_subscriptions([subscription_id]) # Aggregate AFTER acquiring the shared parent lock. Independent node # rows are not sufficient to serialize a subscription-wide total. totals = UsageRecord.objects.filter(subscription_id=subscription_id).aggregate( upload=Sum("upload_bytes"), download=Sum("download_bytes"), ) Subscription.objects.filter(pk=subscription_id).update( upload_bytes=totals["upload"] or 0, download_bytes=totals["download"] or 0, ) @receiver(post_save, sender=UsageRecord) def usage_saved(sender, instance, **kwargs): recompute_subscription_usage(instance.subscription_id) @receiver(post_delete, sender=UsageRecord) def usage_deleted(sender, instance, **kwargs): recompute_subscription_usage(instance.subscription_id)