简体   繁体   English

怎么写提前Django ORM查询

[英]How write advance Django ORM query

To simplify things, lets say I have a models StockIOLog. 为了简化,我们假设我有一个模型StockIOLog。

class StockIOLog(models.Model):
    pid = models.IntegerField()
    name= models.CharField(max_length=50)
    type= models.IntegerField()
    stock = models.IntegerField()

It contains following data: 它包含以下数据:

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

type 0 means product was purchased, type 1 means product was consumed, Now I want to calculate total stock of every product batch-wise. 0型表示购买产品,1型表示产品已消耗,现在我想分批计算每种产品的总库存量。

By running following SQL query 通过运行以下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

I get following queryset 我得到以下queryset

pid  |   name  |  batch | stock
-----------------------------------
1    |   Napa  |  AB    | 85
-----------------------------------
1    |   Napa  |  AA    | 80
-----------------------------------
2    |   Amod  |  AA    | 40
-----------------------------------
2    |   Amod  |  CA    | 80

How to do similar things in django ORM? 如何在django ORM中做类似的事情?

Maybe not the best answer, but You can get purchased and consumed in dictionary by following query 也许不是最好的答案,但您可以通过以下查询在字典中purchasedconsumed

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())))
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM