I have many objects and 3 of them have name='AAA'
I group them by 'name' and annotate num in group:
my_models = MyModel.objects.order_by('name').values('name').annotate(count=Count('name'))
for i in my_models:
print(i.count, i.name)
I get:
3, 'AAA'
1, 'BBB'
...
Everything is fine, but when I try to add some formula to annotate Count():
my_models = MyModel.objects.order_by('name').values('name').annotate(count=Count('name') / 2)
I get:
1, 'AAA'
0, 'BBB'
...
But expected:
1.5, 'AAA'
0.5, 'BBB'
...
EDIT:
Python division differs from SQL division through Django's ORM, so 2/1 in python 3 returns 2.0 - OK, but not in SQL
/ 2.0
? – ArstCast
, see this answer. On Django 1.8+, you might be able to useExpressionWrapper
. – Monophony