问题
How can i convert this query to django ORM query.
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
Actually i want to get all the latest value based on other column value.
For example My table is like -
c1 | c2 | c3
- - - - - - -
x | 1 AM | d1
x | 2 AM | d2
x | 3 AM | d3
y | 1 AM | d4
y | 2 AM | d5{
Desired output :
[{c1: x, c2: 3AM, c3: d3}, {c1: y, c2: 2AM, c3: d5}]
回答1:
You'll have an easier time doing this with a more normalized data model. Consider using an approach like this:
class NodeGroup(model.Model):
pass
class NodeHealth(model.Model):
node_group = models.ForeignKey(NodeGroup, related_name='nodes')
health_time = models.IntegerField()
status = models.IntegerField()
Then you could do this:
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'))
Unfortunately at that point, the nodes returned will have duplicates based if more than one node has the same value for health_time
. You might be able to add a .distinct('node_group_id')
that could clear that up, but I'm not 100% positive.
回答2:
If your database supports analytics, you could do something like this:
q = NodeHealth.objects.extra(
select={'row_num': "ROW_NUMBER() OVER (PARTITION BY c1 ORDER BY c2 DESC)"},
where=["row_num=1"]
)
来源:https://stackoverflow.com/questions/26653360/django-self-join-how-to-convert-this-query-to-orm-query