Skip to content

Commit

Permalink
Allow same annotation to be used several times by stats
Browse files Browse the repository at this point in the history
When using the same annotations twice as stats, it does not work. See tests/test_stats/StatsTest/test_animals_annotation_duplicates
  • Loading branch information
Pieter van Beerendonk authored and BBooijLiewes committed Nov 12, 2024
1 parent bdd29e4 commit fc40658
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 8 deletions.
3 changes: 2 additions & 1 deletion binder/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
24 changes: 18 additions & 6 deletions tests/test_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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': {},
}
})
1 change: 1 addition & 0 deletions tests/testapp/models/animal.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,4 @@ class Annotations:
Value(request.GET.get('animal_name_prefix', 'Sir') + ' '),
F('name'),
))
magic_number = Value(2)
10 changes: 9 additions & 1 deletion tests/testapp/views/animal.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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'],
),
}

0 comments on commit fc40658

Please sign in to comment.