简体   繁体   English

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

[英]Django annotate min and max of filtered foreign key

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

In Django 1.11.13 with mysql as database, i want to optimize the following lines of code: 在以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))

in something like: 在类似:

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 = list of stocks prices variation in the last hour) (stock_deltas =最近一小时的股票价格变动列表)

Is it possible to do such thing? 有可能这样做吗? Otherwise, how can i write the first chunk of code, using the least amount of querys? 否则,如何使用最少的查询量编写第一段代码?

You can combine Max and Min with Q objects for complex filtering 您可以将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'))

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

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