基于其他字段值的字段差异?
Difference on field based on other field value?
这是我的模型:
class InAndOut(models.Model):
quantity = models.FloatField()
date= models.DateField(null=True)
type = models.CharField(max_length=12)
id_product = models.ForeignKey(Products, on_delete=models.CASCADE)
我想查询基于 id_product 的不同值,并针对每个值查询基于类型字段("in" 或 "out")的差异数量:
所以一个真实的例子看起来像:
quantity = 1500
type = In
id_product = Gas
quantity = 300
type = Out
id_product = Gas
query - Gas 1200
请使用此代码。
qs =InAndOut.objects.filter(id_product='Gas')
diff_value=(qs.filter(types='In').annotate(Sum('quantity')).values()[0]['quantity__sum'] - qs.filter(types='Out').annotate(Sum('quantity')).values()[0]['quantity__sum'])
这段代码对我有用。
这是我的模型:
class InAndOut(models.Model):
quantity = models.FloatField()
date= models.DateField(null=True)
type = models.CharField(max_length=12)
id_product = models.ForeignKey(Products, on_delete=models.CASCADE)
我想查询基于 id_product 的不同值,并针对每个值查询基于类型字段("in" 或 "out")的差异数量:
所以一个真实的例子看起来像:
quantity = 1500
type = In
id_product = Gas
quantity = 300
type = Out
id_product = Gas
query - Gas 1200
请使用此代码。
qs =InAndOut.objects.filter(id_product='Gas')
diff_value=(qs.filter(types='In').annotate(Sum('quantity')).values()[0]['quantity__sum'] - qs.filter(types='Out').annotate(Sum('quantity')).values()[0]['quantity__sum'])
这段代码对我有用。