diff --git a/binder/views.py b/binder/views.py index f2e3d973..66f355da 100644 --- a/binder/views.py +++ b/binder/views.py @@ -2985,12 +2985,13 @@ def stats_view(self, request): stats = stats.split(',') return JsonResponse({ - stat: self._get_stat(request, queryset, stat, annotations, include_annotations) + stat: self._get_stat(request, queryset, stat, annotations.copy(), include_annotations) for stat in stats }) def _get_stat(self, request, queryset, stat, annotations, include_annotations): + # NOTE: uses annotations! If called multiple times, provide a copy # Get stat definition try: stat = self.stats[stat] diff --git a/tests/test_stats.py b/tests/test_stats.py index 4cd30e64..2bd66c49 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -86,13 +86,25 @@ def test_stat_not_found(self): 'debug': ANY(), }) - def test_animals_by_zoo(self): - res = self.get_stats('by_zoo') + # annotations + def test_animals_annotation(self): + res = self.get_stats('stat_total_magic_number') self.assertEqual(res, { - 'by_zoo': { - 'value': {'Zoo 1': 1, 'Zoo 2': 2}, - 'other': 0, + 'stat_total_magic_number': { + 'value': 6, 'filters': {}, - 'group_by': 'zoo.name', }, }) + + def test_animals_annotation_duplicates(self): + res = self.get_stats('stat_total_magic_number,stat_total_magic_number_times_hunderd') + self.assertEqual(res, { + 'stat_total_magic_number': { + 'value': 6, + 'filters': {}, + }, + 'stat_total_magic_number_times_hunderd': { + 'value': 600, + 'filters': {}, + } + }) diff --git a/tests/testapp/models/animal.py b/tests/testapp/models/animal.py index 08769ac6..fde79d7b 100644 --- a/tests/testapp/models/animal.py +++ b/tests/testapp/models/animal.py @@ -35,3 +35,4 @@ class Annotations: Value(request.GET.get('animal_name_prefix', 'Sir') + ' '), F('name'), )) + magic_number = Value(2) diff --git a/tests/testapp/views/animal.py b/tests/testapp/views/animal.py index 6f32a639..464b7656 100644 --- a/tests/testapp/views/animal.py +++ b/tests/testapp/views/animal.py @@ -1,4 +1,4 @@ -from django.db.models import Count, Value +from django.db.models import Count, Value, Sum from binder.views import ModelView, Stat @@ -20,4 +20,12 @@ class AnimalView(ModelView): Count(Value(1)), group_by='zoo.name', ), + 'stat_total_magic_number': Stat( + Sum('magic_number'), + annotations=['magic_number'], + ), + 'stat_total_magic_number_times_hunderd': Stat( + Sum('magic_number')*100, + annotations=['magic_number'], + ), }