from django.db.models import F, Avg, Value, FloatField, ExpressionWrapper
from django.db.models.functions.comparison import NullIf
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()
)
)