Django:层次模型查询
Django: Hierarchy model query
假设有一个模型:
class OrgUnit(models.Model):
parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
verbose_name=_('parent'),
related_name='children',
blank=True,
null=True,
)
name = models.CharField(_('name'), max_length=255)
type = models.CharField(_('type'), max_length=55, null=True, blank=True, db_index=True)
层次结构示例:
如果知道集群 ID (cluster_id=1
),很容易找到所有商店:
stores = OrgUnit.objects.filter(
type='store',
parent__parent_id=cluster_id
)
也很容易通过销售部门 ID (sales_department_id=5
) 找到集群:
cluster = OrgUnit.objects.select_related('parent__parent').get(pk=sales_department_id).parent.parent
最后找到销售部门的店铺:
cluster_id = OrgUnit.objects.select_related('parent').get(pk=sales_department_id).parent.parent_id
stores = OrgUnit.objects.filter(type='store', parent__parent_id=cluster_id)
通过销售部门 ID 获取商店将对数据库进行 2 次查询。我想知道是否可以在一次查询中通过销售部门 ID 获取商店?如果是怎么办?
您可以使用 children
再次向下移动层次结构,因此反向查询 ForeignKey
关系:
stores = OrgUnit.objects.filter(
type='store',
<strong>parent__parent__children__children__pk=sales_department_id</strong>
)
因此,我们在这里查询 OrgItem
的父项有一个父项有一个子项,子项有一个主键为 sales_department_id
.
假设有一个模型:
class OrgUnit(models.Model):
parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
verbose_name=_('parent'),
related_name='children',
blank=True,
null=True,
)
name = models.CharField(_('name'), max_length=255)
type = models.CharField(_('type'), max_length=55, null=True, blank=True, db_index=True)
层次结构示例:
如果知道集群 ID (cluster_id=1
),很容易找到所有商店:
stores = OrgUnit.objects.filter(
type='store',
parent__parent_id=cluster_id
)
也很容易通过销售部门 ID (sales_department_id=5
) 找到集群:
cluster = OrgUnit.objects.select_related('parent__parent').get(pk=sales_department_id).parent.parent
最后找到销售部门的店铺:
cluster_id = OrgUnit.objects.select_related('parent').get(pk=sales_department_id).parent.parent_id
stores = OrgUnit.objects.filter(type='store', parent__parent_id=cluster_id)
通过销售部门 ID 获取商店将对数据库进行 2 次查询。我想知道是否可以在一次查询中通过销售部门 ID 获取商店?如果是怎么办?
您可以使用 children
再次向下移动层次结构,因此反向查询 ForeignKey
关系:
stores = OrgUnit.objects.filter(
type='store',
<strong>parent__parent__children__children__pk=sales_department_id</strong>
)
因此,我们在这里查询 OrgItem
的父项有一个父项有一个子项,子项有一个主键为 sales_department_id
.