Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

divide by zero errors when using annotate

# Use NullIf on the Denominator or Divisor
from django.db.models.functions.comparison import NullIf
from django.db.models import F, Avg, Value, FloatField, ExpressionWrapper

context['stock_margin'] = context['top_stock'].annotate(
    Avg_purchase = ExpressionWrapper(
        F('total_puchase') / NullIf(F('quantity_purchase'), 0),
        output_field=FloatField()
    ),
    Avg_sales = ExpressionWrapper(
        F('total') / NullIf(F('quantity'), 0),
        output_field=FloatField()
    )
)
 
PREVIOUS NEXT
Tagged: #divide #errors #annotate
ADD COMMENT
Topic
Name
8+8 =