Django注释已过滤外键的最小值和最大值

时间:2018-10-15 13:13:10

标签: python mysql django optimization annotations

class Price(models.model):
    value = models.DecimalField(...)
    stock = models.ForeignKey("Stock", related_name='prices')

class Stock(models.model):
    current_evlauation = models.ForeignKey('Price')
    last_hour_evlauation = models.ForeignKey('Price')

在以MySQL作为数据库的Django 1.11.13中,我想优化以下代码行:

last_hour = datetime.datetime.now() - datetime.timedelta(hours=2)
stock_list = Stock.objects.all()

for stock in stock_list:
    stock.last_hour_evaluation = stock.prices.filter(date__gte=last_hour).earliest('date')
    stock.current_evaluation = stock.prices.latest('date')
    stock.save()

stock_deltas = list(Stock.objects.annotate(delta=F('current_evaluation__value)-F('last_hour_evaluation__value')).values_list('delta', flat=True))

类似:

stock_deltas = list(Stock.objects\
                         .annotate(current_eval=..., last_eval=...)\
                         .annotate(delta=F('current_eval') -F('last_hour_eval'))\
                         .values_list('delta', flat=True))

(stock_deltas =最近一小时的股票价格变化列表)

有可能这样做吗? 否则,如何使用最少的查询量来编写第一段代码?

1 个答案:

答案 0 :(得分:0)

您可以将MaxMinQ objects结合使用以进行复杂的过滤

Stock.objects.all().annotate(
    current_eval=Min('prices__date', filter=Q(prices__date__gte=last_hour)),
    last_eval=Max('prices__date')).annotate(
    delta=F('current_val') - F('last_eval'))