1

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)
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Post your `models.py` here. – Astik Anand Mar 01 '18 at 03:27
  • You tried to access `child.lft` but, I couldn't find any `lft` attribute in your `Organization` model. Am I missing something? – JPG Mar 01 '18 at 03:55
  • @JerinPeterGeorge lft, rgt values get generated automatically. See Organization is the child class of `NS_Node` class https://github.com/django-treebeard/django-treebeard/blob/3c87f481c19b096db0d0b2cd646fa6e95f66eab9/treebeard/ns_tree.py#L114 – Avinash Raj Mar 01 '18 at 04:22
  • If this is something you need to do regularly, you might consider another tree algorithm. MPTT (via django-mptt) stores the parent_id as a field on the model, so no extra lookups are required. – Daniel Roseman Mar 01 '18 at 10:44

0 Answers0