Search code examples
djangodjango-ormdjango-annotate

Django's annotate Count with division returns integer instead of float


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


Solution

  • Full answer following @Alasdair's comment:

    from django.db.models import FloatField
    from django.db.models.functions import Cast
    
    qs = MyModel.objects.order_by('name').values('name').annotate(
        count=Cast(Count('name') / 2.0, FloatField()))