如何对另一个查询集/查询进行INNER JOIN

时间:2019-07-05 04:43:02

标签: python django

我对Django ORM有问题。我有一个天气模型:

    class Weather(models.Model):
        city = models.ForeignKey(City, verbose_name='Город', on_delete=models.CASCADE)
        temperature = models.FloatField('Температура')
        source = models.CharField('Источник', max_length=100)
        date = models.DateTimeField('Дата и время')

我想从每个城市的各个来源获取实际天气。我为此创建了sql查询,但不了解如何使用Django ORM。

查询:

SELECT * FROM api_weather t1 INNER JOIN
(
    SELECT MAX(date) AS latest_date, city_id, source FROM api_weather WHERE date<='2019-07-04 15:50' GROUP BY city_id, source
) t2
ON t1.city_id = t2.city_id AND t1.source = t2.source AND t1.date = t2.latest_date

我意识到该怎么做

SELECT MAX(date) AS latest_date, city_id, source FROM api_weather WHERE date<='2019-07-04 15:50' GROUP BY city_id, source

使用Django ORM,它是

Weather.objects.filter(date__lte=datetime.datetime.now()).values('city_id', 'source').annotate(latest_date=Max('date'))

但是我不知道如何从Weather模型向该查询执行INNER JOIN。

1 个答案:

答案 0 :(得分:0)

Weather.objects.values('city', 'source', 'temperature').annotate(latest_date=Max('date'))