简体   繁体   中英

django select_related tree path

I have a django model that represents edges of a tree and a model that represents the nodes:

class Edge(models.Model):
nodeFrom = models.ForeignKey('Node', related_name='+')
nodeTo = models.ForeignKey('Node', related_name='+')

class Node(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.TextField()
    parentNode = models.ForeignKey('Node', null=True)

Is there a way to build tree paths for a subtree with only one database hit?

I tried this:

userEdges = Edge.objects.filter(nodeFrom__in=userNodes, nodeTo__in=userNodes).select_related('nodeFrom', 'nodeTo)

but if I try to build the path like this,

def get_path(node, userEdges):
    path = [node]
    while path[-1].parentNode_id != None:   
        path.append(userEdges.get(nodeTo=node).nodeFrom)

    return path

a database access is always caused by that line:

userEdges.get(nodeTo=node).nodeFrom

That's because your using .get . Since you've already retrieved the userEdges and have them in memory, you can do:

while ... :
    currentEdge = next(e for e in userEdges if e.nodeTo == node)
    path.append(currentEdge.nodeFrom)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM