From 7ec1c726a6ca3c7e53098c5a53273f94810c6229 Mon Sep 17 00:00:00 2001 From: Tom Price Date: Wed, 1 Mar 2017 02:42:39 +0000 Subject: [PATCH] Optimise down to just the one SQL query for waiting invoices. Cuts down on all the unnecessary queries and selects everything in one go. Down from ~6 queries per invoice --- RIGS/finance.py | 12 +++++++----- RIGS/models.py | 8 +++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/RIGS/finance.py b/RIGS/finance.py index f8d23f58..00786c62 100644 --- a/RIGS/finance.py +++ b/RIGS/finance.py @@ -1,6 +1,7 @@ import cStringIO as StringIO import datetime import re +from decimal import Decimal from django.contrib import messages from django.core.urlresolvers import reverse_lazy @@ -31,12 +32,13 @@ class InvoiceIndex(generic.ListView): def get_queryset(self): query = self.model.objects.annotate( - cost=Sum(F('event__items__cost') * F('event__items__quantity'), output_field=FloatField()), - payment_count=Count('payment'), - payments=Sum('payment__amount'), + _sum_total=Sum(F('event__items__cost') * F('event__items__quantity'), output_field=FloatField()), + _payment_count=Count('payment'), + _payment_total=Sum('payment__amount'), ).filter( - Q(cost__gt=0.0, payment_count=0) | Q(cost__lt=Value('payments'), cost__gt=Value('payments')) - ).select_related('event', 'event__organisation', 'event__person', 'event__venue') + Q(_sum_total__gt=0.0, _payment_count=0) | + Q(_sum_total__lt=Value('_payment_total'), _sum_total__gt=Value('_payment_total')) + ).select_related('event', 'event__organisation', 'event__person', 'event__venue', 'event__mic') return query diff --git a/RIGS/models.py b/RIGS/models.py index 0650d81c..6aa16730 100644 --- a/RIGS/models.py +++ b/RIGS/models.py @@ -1,11 +1,11 @@ import datetime import hashlib -import pytz import random import string from collections import Counter from decimal import Decimal +import pytz import reversion from django.conf import settings from django.contrib.auth.models import AbstractUser @@ -509,6 +509,8 @@ class Invoice(models.Model): @property def sum_total(self): + if getattr(self, '_sum_total', None): + return Decimal(getattr(self, '_sum_total')) return self.event.sum_total @property @@ -517,6 +519,10 @@ class Invoice(models.Model): @property def payment_total(self): + if hasattr(self, '_payment_total') and hasattr(self, '_payment_count'): + if getattr(self, '_payment_count') == 0: + return Decimal(0.00) + return Decimal(getattr(self, '_payment_total', 0.00)) total = self.payment_set.aggregate(total=models.Sum('amount'))['total'] if total: return total