这是我的模特
class Stockdata(models.Model):
stock_name = models.CharField(max_length=32,unique=True)
class Stock_Total_sales(models.Model):
sales = models.ForeignKey(Sales,on_delete=models.CASCADE,null=True,blank=False,related_name='saletotal')
stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='salestock')
quantity = models.PositiveIntegerField()
class Stock_Total(models.Model):
purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal')
stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock')
quantity_p = models.PositiveIntegerField()
我想计算购买和销售的数量,并在带注释的值之间进行减法。
所以,我这样做了:
qs = Stockdata.objects.annotate(
sales_sum = Subquery(
Stock_Total_sales.objects.filter(
sales = OuterRef('pk')
).values(
'sales'
).annotate(
the_sum = Sum('quantity')
).values('the_sum')
),
purchase_sum = Coalesce(Sum('purchasestock__quantity_p'),0)
)
qs1 = qs.annotate(
difference = ExpressionWrapper(F('purchase_sum') - F('sales_sum'), output_field=DecimalField())
但是sales_sum的值即将到来NONE子查询或其他任何问题吗?
任何人都可以告诉我我在代码中犯了什么错误。
谢谢