为简化起见,我们假设我有一个型号StockIOLog。
class StockIOLog(models.Model):
pid = models.IntegerField()
name= models.CharField(max_length=50)
type= models.IntegerField()
stock = models.IntegerField()
它包含以下数据:
pid | name | batch | type | quantity
------------------------------------------------
1 | Napa | AB | 0 | 100
------------------------------------------------
1 | Napa | AA | 0 | 100
------------------------------------------------
2 | Amod | AA | 0 | 100
------------------------------------------------
2 | Amod | CA | 0 | 100
------------------------------------------------
1 | Napa | AB | 1 | 10
------------------------------------------------
1 | Napa | AB | 1 | 5
------------------------------------------------
1 | Napa | AA | 1 | 20
------------------------------------------------
2 | Amod | AA | 1 | 10
------------------------------------------------
2 | Amod | AA | 1 | 50
------------------------------------------------
2 | Amod | CA | 1 | 5
------------------------------------------------
2 | Amod | CA | 1 | 15
0型表示购买产品,1型表示产品已消耗,现在我想分批计算每种产品的总库存量。
运行以下SQL查询
SELECT pid, name, batch, SUM(in) - SUM(out) as stock FROM (
SELECT pid, name, type SUM(quantity) as in, 0 as out from `qset` WHERE type=0 GROUP BY pid,type,batch as a
UNION
SELECT pid, name, type 0 as in, SUM(quantity) as out from `qset` WHERE type=1 GROUP BY pid,type,batch as b
) ac table_a
我得到以下queryset
pid | name | batch | stock
-----------------------------------
1 | Napa | AB | 85
-----------------------------------
1 | Napa | AA | 80
-----------------------------------
2 | Amod | AA | 40
-----------------------------------
2 | Amod | CA | 80
如何在django ORM中做类似的事情?
答案 0 :(得分:0)
也许不是最佳答案,但您可以通过以下查询在字典中获取purchased
和consumed
from django.db.models import When, F, IntegerField, Sum, Count
from .models import StockIOLog
values = (StockIOLog.objects.all().values("pid", "name", "batch").annotate(
purchased=Sum(Case(When(type=1, then=F("stock")),
output_filed=IntegerField())),
consumed=Sum(Case(When(type=0, then=F("stock")),
output_field=IntegerField())))
)