Tuesday, 15 September 2015

python - Django self join , How to convert this query to ORM query -



python - Django self join , How to convert this query to ORM query -

how can convert query django orm query.

select t.node_id, ht, status, info ( select id, max(health_time) ht, node_id remote_sense_nodehealth grouping node_id ) t bring together remote_sense_nodehealth on remote_sense_nodehealth.health_time=t.ht , remote_sense_nodehealth.node_id = t.node_id

actually want latest value based on other column value.

for illustration table -

c1 | c2 | c3 - - - - - - - x | 1 | d1 x | 2 | d2 x | 3 | d3 y | 1 | d4 y | 2 | d5{

desired output :

[{c1: x, c2: 3am, c3: d3}, {c1: y, c2: 2am, c3: d5}]

you'll have easier time doing more normalized info model. consider using approach 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 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 @ point, nodes returned have duplicates based if more 1 node has same value health_time. might able add together .distinct('node_group_id') clear up, i'm not 100% positive.

python mysql django django-orm

No comments:

Post a Comment