from django.core.management.base import BaseCommand, CommandError from django.db.models import DecimalField, F, Sum, Func, Q from decimal import Decimal from services.models import ServiceType class Command(BaseCommand): help = 'Bénéfices des services' def handle(self, *args, **options): as_float_template = '%(function)s(%(expressions)s AS FLOAT)' total_income = Decimal(0.0) lines = [] for service_type in ServiceType.objects.all(): services = service_type.services ntotal = services.count() services = services.exclude(adherent=None) nadh = services.count() ninf = ntotal - nadh services = services.exclude(Q(contribution__isnull=True) | Q(contribution__amount=0) | Q(contribution__period=0)) npay = services.count() ngra = nadh - npay amount = Func(F('contribution__amount'), function='CAST', template=as_float_template) period = F('contribution__period') output_field = DecimalField(max_digits=9, decimal_places=2) income = services.aggregate(income=Sum(amount / period, output_field=output_field))['income'] or Decimal(0.0) total_income += income lines += [(str(service_type), npay, ninf, ngra, income,)] self.stdout.write("%-16s%12s%12s%12s%12s%12s" % ('Service', 'npay', 'ninf', 'ngra', 'eur', 'pourcent')) for service_type, npay, ninf, ngra, income in lines: if total_income: percent = income / total_income * 100 else: percent = 0 self.stdout.write("%-16s%12d%12d%12d%12.2f%12.1f" % (service_type, npay, ninf, ngra, income, percent))