我有一个树形层次结构,如下所示:
1. Tree
-name
-location
-branch_count
-leaf_count
2. Branch
-tree (foreign key to tree)
-length
-leaf_count
3. Leaf
-branch (foreign key to branch)
字段branch_count
和leave_count
基本上都是缓存。我已将信号附加到Branch
和Leaf
模型,以便在创建/删除/保存一个模型时,它会向上移动树并更新leaf_count
和/或branch_count
在父对象上。
这非常有用,因为如果我创建一个新的Leaf
,它会更新Branch
实例上的计数,并且因为这会保存Branch
实例,所以信号会更新Tree
1}}。
信号看起来像这样:
@receiver(signals.post_save, sender=Leaf)
@receiver(signals.post_delete, sender=Leaf)
def branch_metadata_update(sender, instance, **kwargs):
branch = instance.branch
branch.leaf_count = branch.leaf_set.count()
branch.save()
@receiver(signals.post_save, sender=Branch)
@receiver(signals.post_delete, sender=Branch)
def tree_metadata_update(sender, instance, **kwargs):
tree = instance.tree
leaf_count = 0
branch_count = 0
branches = tree.branch_set.all()
for branch in branches:
branch_count += 1
leaf_count += branch.leaf_count
tree.leaf_count = leaf_count
tree.branch_count = branch_count
tree.save()
我唯一没想到的是当Leaf
从Branch
移动到另一个Leaf
时如何使其正常工作。当然,保存{{1}}时信号会触发,但由于Leaf已经分配了一个新的分支,它不知道重建旧分支,甚至不知道旧分支是什么。
任何人都想知道解决这个问题的好方法吗?