Django:两列之和的最大值

时间:2018-06-16 18:57:58

标签: django django-models

我需要两列总和的最大值,如果有几行具有相同的价格,我想要一个具有最新日期的行。

models.py

from django.db import models
from django.utils import timezone

# Create your models here.


class Flight(models.Model):
    outboundPrice = models.FloatField()
    returnPrice = models.FloatField()
    timeCreated = models.DateTimeField(default=timezone.now)

我目前正在使用此查询:

>>> Flight.objects.values('timeCreated').annotate(max=Max(F('outboundPrice') + F('returnPrice'))).order_by('-max')[0]
{'timeCreated': datetime.datetime(2018, 6, 16, 13, 0, 12, 525111, tzinfo=<UTC>), 'max': 205}

将以下MySQL查询转换为两个:

mysql [lab]> SELECT timeCreated, MAX((outboundPrice + returnPrice)) AS max FROM flights_flight GROUP BY timeCreated ORDER BY timeCreated ASC LIMIT 1;
+----------------------------+--------------------+
| timeCreated                | max                |
+----------------------------+--------------------+
| 2018-06-16 13:00:12.525111 | 205.98000000000002 |
+----------------------------+--------------------+
1 row in set (0.00 sec)

但那不是最近的那个:

mysql [wizzair]> SELECT timeCreated, MAX((outboundBasePrice + returnBasePrice)) AS max FROM flights_result GROUP BY timeCreated ORDER BY timeCreated ASC;
+----------------------------+--------------------+
| timeCreated                | max                |
+----------------------------+--------------------+
| 2018-06-16 13:00:12.525111 | 205.98000000000002 |
| 2018-06-16 14:00:13.404816 | 205.98000000000002 |
| 2018-06-16 15:00:12.927219 | 205.98000000000002 |
| 2018-06-16 16:00:12.595076 | 205.98000000000002 |
| 2018-06-16 17:00:11.226041 | 205.98000000000002 |
| 2018-06-16 18:00:12.692635 | 205.98000000000002 |
| 2018-06-16 19:47:51.000000 | 201.98000000000002 |
+----------------------------+--------------------+
7 rows in set (0.00 sec)

基本上我想查询两种方式的票最便宜的日期。

1 个答案:

答案 0 :(得分:2)

您可以添加额外的订购标准

Flight.objects.values('timeCreated').annotate(
    max=Max(F('outboundPrice') + F('returnPrice'))
).order_by('-max', '-timeCreated').first()

因此,如果是 tie ,我们也会在timereated上按降序排序,以便选择最新的。

如果您想要第一个条目,可以使用.first(),这更加自我解释。如果没有这样的行,它将返回None