场景:我有一个模型,被其它多个模型关联,我配置了CASCADE级联删除,我想要告知用户删除该实例之后,哪些关联数据将会被一同删除。
假设我们当前有这样一组模型:
class Warehouse(models.Model):
"""仓库"""
...
class OutboundRecord(models.Model):
"""出库单"""
warehouse = models.ForeignKey('Warehouse', on_delete=models.CASCADE, verbose_name="仓库")
...
class OutboundList(models.Model):
"""出库单明细"""
warehouse = models.ForeignKey('Warehouse', on_delete=models.CASCADE, verbose_name="仓库")
...
class InboundRecord(models.Model):
"""入库单"""
warehouse = models.ForeignKey('Warehouse', on_delete=models.CASCADE, verbose_name="仓库")
...
class InboundList(models.Model):
"""入库明细"""
warehouse = models.ForeignKey('Warehouse', on_delete=models.CASCADE, verbose_name="仓库")
...
它们的关系如下:
想要查询warehouse所有关联数据的方法很简单,具体代码如下:
from django.contrib.admin.utils import NestedObjects
from xxx import Warehouse
o = NestedObjects(using='default')
o.collect(Warehouse.object.all())
print(o.nest())
假设我们事先已经插入了一些数据,上述代码会输出一个嵌套数组结构,所有的关系一目了然,嵌套数组的处理也很轻松,根据你的需要进行递归遍历即可。
[
<Warehouse: 仓库1>,
[
<OutboundRecord: OutboundRecord object (2)>,
[
<OutboundList: OutboundList object (2)>,
<OutboundList: OutboundList object (5)>,
<OutboundList: OutboundList object (8)>
],
<OutboundRecord: OutboundRecord object (3)>,
[
<OutboundList: OutboundList object (3)>,
<OutboundList: OutboundList object (6)>,
<OutboundList: OutboundList object (9)>
],
<InboundRecord: InboundRecord object (1)>,
[
<InboundList: InboundList object (1)>,
<InboundList: InboundList object (4)>,
<InboundList: InboundList object (7)>
]
],
<Warehouse: 仓库2>,
[
<OutboundRecord: OutboundRecord object (1)>,
[
<OutboundList: OutboundList object (1)>,
<OutboundList: OutboundList object (4)>,
<OutboundList: OutboundList object (7)>
],
<InboundRecord: InboundRecord object (2)>,
[
<InboundList: InboundList object (2)>,
<InboundList: InboundList object (5)>,
<InboundList: InboundList object (8)>
],
<InboundRecord: InboundRecord object (3)>,
[
<InboundList: InboundList object (3)>,
<InboundList: InboundList object (6)>,
<InboundList: InboundList object (9)>
]
],
<Warehouse: 仓库3>
]
NestedObjects的collect方法来自父类Collector,不过NestedObjects中多来nest()方法帮我们构建方便的层级结构。