【发布时间】:2018-10-28 15:26:28
【问题描述】:
给定一个模型
class Entity(models.Model):
identifier = models.IntegerField()
created = models.IntegerField()
content = models.IntegerField()
class Meta:
unique_together = (('identifier', 'created'))
我想查询所有created 为最大的对象,在具有共同identifier 的对象中。
在 SQL 中,子查询中的窗口函数解决了这个问题:
SELECT identifier, content
FROM entity
WHERE (identifier, created)
IN (SELECT identifier, max(created) OVER (PARTITION BY identifier)
FROM entity);
另请参阅:http://sqlfiddle.com/#!17/c541f/1/0
窗口函数和子查询在 Django 2.0 中都可用。但是,我还没有找到一种方法来表达具有多列的子查询表达式。
有没有办法将该 SQL 查询转换为 Django QuerySet 世界?这可能是一个 XY 问题,我的问题可以通过不同的方式解决吗?
我丑陋的解决方法是
Entity.objects.raw('''
SELECT * FROM app_entity e
WHERE e.created = (SELECT max(f.created) FROM app_entity f WHERE e.identifier = f.identifier)''')
因为底层的 sqlite3 版本显然不能处理多列子查询。
【问题讨论】: