0

I have a Django 1.9 queryset qs to which I add the following annotations:

qs = qs.annotate(total_messages=
    Sum(Case(..., output_field=FloatField()))

qs = qs.annotate(spam_messages=
    Sum(Case(..., output_field=FloatField()))

qs = qs.annotate(spam_rate=F('spam_messages')/F('total_messages'))

Weirdly, the results seem to be rounded downwards (like Math.floor), so that I get the following results (examples):

total_messages = 40.0, spam_messages = 24.0, spam_rate = 0.0
total_messages = 10.0, spam_messages = 10.0, spam_rate = 1.0

Also, it might be the case this behavior only occurred after upgrading from Django 1.7 to Django 1.9.

Am I doing something wrong or is that a bug?

Thanks in advance!

Se Norm
  • 1,715
  • 5
  • 23
  • 40

1 Answers1

0

Ok, found the problem thanks to lac's comment:

Inside the Case(...) I have statements like this:

When(
    message__date__gte=one_month_ago,
    then=1
    )

If I change the 1 to 1.0 everything work as expected.

Still, this looks like a bug to me, especially since I specify output_field=FloatField(), but even with IntegerFields I believe the division should return a decimal, shouldn't it?

Se Norm
  • 1,715
  • 5
  • 23
  • 40