I have one Organization model in which for each organization, I have to find it's parent organization's id.
I can able to get the parent org's id for a single organization using this piece of code,
child = Organization.objects.filter(name='XYZ').first()
parent = Organization.objects.filter(lft__lt=child.lft, rgt__gt=child.rgt, tree_id=child.tree_id).order_by('depth').last()
print child, parent.id
But I want the same for each organization (for each org, I want it's parent id).. If I do in a for loop, there should be an n number of db queries generated. Is there any way to get the output in a single db query?
models.py
from treebeard.ns_tree import NS_Node
class Organization(NS_Node):
name = models.CharField(max_length=100, null=False)
url = models.URLField(default=None, blank=True, unique=True, null=True)
image = models.ForeignKey(Image, blank=True, null=True)
is_organization = models.BooleanField(default=False)
is_unit = models.BooleanField(default=False)
is_lob = models.BooleanField(default=False)
is_function = models.BooleanField(default=False)
is_department = models.BooleanField(default=False)