【发布时间】:2018-08-23 17:19:45
【问题描述】:
鉴于这个 django 模型:
def Price(model.Model):
date = models.DateTimeField()
item = models.ForeignKey('Item', on_delete=models.CASCADE)
price = models.IntegerField(blank=True, null=True)
我们的目标是获取可以非常简单地查询的每件商品的最新价格。假设 orm 使用的是 postgresql:
Price.objects.all().order_by('date').distinct('item')
当使用其他数据库引擎时,不可能distinct on 特定字段,我想避免将自己锁定在 postgres 中,所以我一直在寻找模拟它的查询。我已经编写/找到了一个可以完成这项工作的查询:
Price.objects.raw('''
SELECT P1.*
FROM `merchapi_pricelog` P1
LEFT JOIN `merchapi_pricelog` P2
ON P1.item_id = P2.item_id AND P1.date < P2.date
WHERE P2.date is NULL
''')
原始查询比在代码中加载和过滤数据要快,但我很想看看是否有更好的方法以不使用原始 sql 的 db-agnostic 方式执行此操作。
【问题讨论】:
标签: sql django postgresql django-models django-orm