0

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.

1 Answer 1

2

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())
            )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.