Django自连接,如何将此查询转换为ORM查询
我该如何把这个查询转换成Django的ORM查询呢?
select T.node_id, ht, status, data from (
select id, Max(health_time) as ht, node_id from remote_sense_nodehealth group by node_id
) as T
join remote_sense_nodehealth on remote_sense_nodehealth.health_time=T.ht and remote_sense_nodehealth.node_id = T.node_id
其实我想根据其他列的值来获取所有最新的值。
比如我的表格是这样的 -
c1 | c2 | c3
- - - - - - -
x | 1 AM | d1
x | 2 AM | d2
x | 3 AM | d3
y | 1 AM | d4
y | 2 AM | d5{
期望的输出结果是:
[{c1: x, c2: 3AM, c3: d3}, {c1: y, c2: 2AM, c3: d5}]
2 个回答
0
如果你的数据库支持分析功能,你可以这样做:
q = NodeHealth.objects.extra(
select={'row_num': "ROW_NUMBER() OVER (PARTITION BY c1 ORDER BY c2 DESC)"},
where=["row_num=1"]
)
1
如果你使用一个更规范的数据模型,事情会变得简单一些。可以考虑用这样的方式:
class NodeGroup(model.Model):
pass
class NodeHealth(model.Model):
node_group = models.ForeignKey(NodeGroup, related_name='nodes')
health_time = models.IntegerField()
status = models.IntegerField()
然后你可以这样做:
from django.db.models import Max, F
nodes = NodeHealth.objects.all().annotate(
max_health_time=Max('node_group__nodes__health_time')
).filter(health_time=F('max_health_time'))
不过到那时,返回的节点可能会有重复,因为如果有多个节点的health_time
值相同,就会出现这种情况。你可以尝试加上.distinct('node_group_id')
来解决这个问题,但我不能完全确定。