From 63c9f381bcb8858ee6add0ac139163a656da9eff Mon Sep 17 00:00:00 2001 From: Marc Aymerich Date: Thu, 16 Jul 2015 13:12:50 +0000 Subject: [PATCH] DRY resources.aggregations --- TODO.md | 2 -- orchestra/contrib/resources/aggregations.py | 26 ++++++--------------- 2 files changed, 7 insertions(+), 21 deletions(-) diff --git a/TODO.md b/TODO.md index e21f5914..d604ba12 100644 --- a/TODO.md +++ b/TODO.md @@ -423,5 +423,3 @@ Colaesce('total', 'computed_total') Case # case on payment transaction state ? case when trans.amount > - -# Yield multiple values on historic filter on all aggregators diff --git a/orchestra/contrib/resources/aggregations.py b/orchestra/contrib/resources/aggregations.py index 1eff699f..e508b462 100644 --- a/orchestra/contrib/resources/aggregations.py +++ b/orchestra/contrib/resources/aggregations.py @@ -34,9 +34,8 @@ class Last(Aggregation): if date is not None: dataset = dataset.filter(created_at__lte=date) return dataset - - def historic_filter(self, dataset): - yield (timezone.now(), self.filter(dataset)) + + def monthly_historic_filter(self, dataset): now = timezone.now() date = datetime.datetime( year=now.year, @@ -54,6 +53,10 @@ class Last(Aggregation): yield (date, dataset_copy) date -= relativedelta(months=1) + def historic_filter(self, dataset): + yield (timezone.now(), self.filter(dataset)) + yield from self.monthly_historic_filter(dataset) + def compute_usage(self, dataset): values = dataset.values_list('value', flat=True) if values: @@ -75,22 +78,7 @@ class MonthlySum(Last): ) def historic_filter(self, dataset): - now = timezone.now() - date = datetime.datetime( - year=now.year, - month=now.month, - day=1, - tzinfo=timezone.utc, - ) - while True: - dataset_copy = copy.copy(dataset) - dataset_copy = self.filter(dataset_copy, date=date) - try: - dataset_copy[0] - except IndexError: - raise StopIteration - yield (date, dataset_copy) - date -= relativedelta(months=1) + yield from self.monthly_historic_filter(dataset) class MonthlyAvg(MonthlySum):