0

我有一个组织模型,对于每个组织,我必须找到它的父组织的 ID。

我可以使用这段代码获取单个组织的父组织的 ID,

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

但是我希望每个组织都相同(对于每个组织,我希望它是父 ID)。如果我在 for 循环中这样做,则应该生成 n 个数据库查询。有没有办法在单个数据库查询中获取输出?

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)
4

0 回答 0