zerohedge
zerohedge

Reputation: 3725

Django: Annotate based on annotations with conditional

I'm doing this at the end of an annotation chain on my queryset:

.annotate(diff=F("total_views")/F("previous_views")

The issue is that both total_views and previous_views are annotations themselves. This is working, except when F("previous_views") equals 0. I then get a division by zero error. All attempts to use Case/When have failed.

I'm looking for a way to calculate diff as a fraction, unless previous_views is 0, in which case diff should be None.

Upvotes: 0

Views: 537

Answers (1)

zerohedge
zerohedge

Reputation: 3725

Apparently, it's possible to use the annotation as if it was a regular field in the When clause:

.annotate(
                diff=Case(
                    When(previous_views__gt=0, then= F("total_views") - F("previous_views"))
                , default=None, output_field=FloatField())
            )

Upvotes: 2

Related Questions