Q:

How to Subtract annoted values in django?

I am unable to subtract annotated values of two different queries in django views.
I tried this:
    qs = Stockdata.objects.filter(User=self.request.user, Company=company_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date)
    total = qs.annotate(the_sum=Coalesce(Sum('salestock__Quantity'),0)).values('the_sum')
    total2 = qs.annotate(the_sum2=Coalesce(Sum('purchasestock__Quantity_p'),0)).values('the_sum2')
    totalqty = total2 - total

I tried using Coalesce from django.db.models.function but getting this error
TypeError: unsupported operand type(s) for -: 'QuerySet' and 'QuerySet'

Is there any function in django to subtract values?
Do anyone have any idea what I am doing wrong in my code?

A:

Try
qs = qs.annotate(
    sales_sum = Coalesce(Sum('salestock__Quantity'),0),
    purchase_sum = Coalesce(Sum('purchasestock__Quantity_p'),0)
)
qs = qs.annotate(
    difference = ExpressionWrapper(F('sales_sum') - F('purchase_sum'), output_field=DecimalField())
) 

