我正在学习Django,并且在StackOverflow上使用文档和其他各种文章已经走了很长一段路,但是现在我有点卡住了。本质上,我想按如下方式查询数据库:
SELECT
w.wname,
w.act_owner_id,
wi.act_code,
wi.act_provider,
SUM(ft.quantity) AS "position",
prices.Current,
prices.MonthEnd,
prices.YearEnd,
cost.avgcost,
sec.securityName AS "security"
FROM
finance_wrapperinstance as wi
INNER JOIN finance_wrapper as w ON
(w.id = wi.wrapperType_id)
INNER JOIN finance_security as sec ON
(ft.security_id = sec.id)
left outer JOIN finance_transaction as ft ON
(wi.id = ft.investwrapperID_id)
left outer Join
(SELECT
hp.security_id as secid,
max(Case when hp.date = '2019-11-18' then hp.price end) as 'Current',
max(Case when hp.date = '2019-10-30' then hp.price end) as 'MonthEnd',
max(Case when hp.date = '2018-12-31' then hp.price end) as 'yearEnd'
FROM finance_historicprice as hp
GROUP BY hp.security_id
) AS prices ON
(prices.secid =ft.security_id)
INNER JOIN
(SELECT
trans.security_id AS secid,
trans.investwrapperID_id as iwID,
SUM((CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END)* trans.price) /
SUM(CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END) AS avgCost
FROM
finance_transaction as trans
GROUP BY
trans.security_id,
trans.investwrapperID_id) AS cost ON
(cost.secid = ft.security_id and cost.iwID = wi.id)
GROUP BY
w.wname,
wi.wrapperType_id,
wi.act_code,
wi.act_provider,
ft.security_id
但是我不知道如何使用Django ORM来获取我的 prices 子查询或 cost 子查询。
模型如下所示:
class Wrapper(models.Model):
wname = models.CharField(max_length=50,null=False,verbose_name="Wrapper Name")
act_owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Wrapperinstance(models.Model):
wrapperType = models.ForeignKey(Wrapper,on_delete=models.CASCADE)
act_code = models.CharField(max_length=50,null=False, verbose_name="Account Code")
act_provider = models.CharField(max_length=50,null=False,verbose_name="Account Provider")
class Security(models.Model):
securityName = models.CharField(max_length=200,null=False,verbose_name="Security Name")
securityType = models.ForeignKey(InstrumentType,on_delete=models.CASCADE)
class Transaction(models.Model):
BUY = 'b'
SELL = 's'
BUY_SELL_CHOICES = [
(BUY, 'Buy'),
(SELL, 'Sell'),
]
security = models.ForeignKey(Security,default=1,on_delete=models.CASCADE)
investwrapperID = models.ForeignKey(Wrapperinstance,default=1,on_delete=models.CASCADE)
quantity = models.DecimalField(max_digits=14, decimal_places=4)
buysell = models.CharField(max_length=2,choices=BUY_SELL_CHOICES, default = BUY)
price = models.DecimalField(max_digits=14, decimal_places=2)
class HistoricPrice(models.Model):
security = models.ForeignKey(Security,default=1,on_delete=models.CASCADE)
date = models.DateField()
price = models.DecimalField(max_digits=14, decimal_places=2)
任何帮助或指针将不胜感激。另外,我有一些函数可以选择要为SQL查询输入的正确日期。这再次使我认为RAW方法可能是可行的方法。