[Fixed]-Conditional annotate on django 1.8 queryset

1👍

You can make conditional expresions with Case.

Let’s go to the annotate part.

Disclaimer: This code is untested

from django.db.models import Case, Value, When, FloatField, Sum

...annotate(mu=Case(When(metric=some_metric, then=Value(.8*Sum('metric_units')),
                    default=Value(Sum('metric_units')),
                    output_field=FloatField())))

If you need to match against multiple values in a list, you can create a list of When objects:

whens = []
for some_metric in some_metrics:
    whens.append(When(metric=some_metric, then=Value(some-value-here)))

...annotate(mu=Case(*whens, default=Value(Sum('metric_units')),
                            output_field=FloatField()))
👤Gocht

Leave a comment