我有一个存储KLine信息的表,包括安全ID,最大/最小价格和日期,并希望计算某个时期内每个证券的收益。这是我的功能
def get_rising_rate(start, end):
return models.KLine.objects.\
filter(start_time__gt=start). \
filter(start_time__lt=end).\
values("security__id").\
annotate(min_price=django_models.Min("min_price_in_cent"),
max_price=django_models.Max("max_price_in_cent")).\
extra(select={"gain": "max_price_in_cent/min_price_in_cent"})
order_by("gain")
但是我收到了以下错误:
django.db.utils.OperationalError: (1247, "Reference 'max_price' not supported (reference to group function)")
我可以使用原始SQL进行查询,如
SELECT
`security_id`,
`min_price`,
`max_price`,
`max_price`/`min_price` AS gain
FROM(
SELECT
`security_id`,
MIN(`min_price_in_cent`) AS `min_price`,
MAX(`max_price_in_cent`) AS `max_price`
FROM `stocks_kline`
WHERE `start_time` > '2014-12-31 16:00:00' AND `start_time` < '2015-12-31 16:00:00'
GROUP BY `security_id`
) AS A
ORDER BY gain DESC
但我想知道是否有更多的“django”方式来完成它。我搜索过“django join queryset”,“django queryset as derived tables”但无法得到解决方案。
提前致谢。
答案 0 :(得分:0)
你可以试试这个:
def get_rising_rate(start, end):
return models.KLine.objects.\
filter(start_time__gt=start). \
filter(start_time__lt=end).\
values("security_id").\
annotate(min_price=django_models.Min("min_price_in_cent"),
max_price=django_models.Max("max_price_in_cent")).\
extra(select={"gain": "max(max_price_in_cent)/min(min_price_in_cent)"})
order_by("gain")