How write advance Django ORM query

Viewed 560

To simplify things, lets say I have a models 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.

By running following SQL query

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

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?

1 Answers
Related