我正在开发一个使用django-mptt的项目,但是当我使用get_ancestors函数时,我得到了奇怪的结果.这是一个例子.
我有一个创建了一个简单的模型,继承自MPTTModel:
class Classifier(MPTTModel):
title = models.CharField(max_length=255)
parent = TreeForeignKey('self', null = True, blank = True,
related_name = 'children')
def __unicode__(self):
return self.title
Run Code Online (Sandbox Code Playgroud)
以下是适用于此模型的功能:
def test_mptt(self):
# Erase all data from table
Classifier.objects.all().delete()
# Create a tree root
root, created = Classifier.objects.get_or_create(title=u'root', parent=None)
# Create 'a' and 'b' nodes whose parent is 'root'
a = Classifier(title = "a")
a.insert_at(root, save = True)
b = Classifier(title = "b")
b.insert_at(root, save = True)
# Create 'aa' and 'bb' nodes whose …Run Code Online (Sandbox Code Playgroud) 我正在创建一个将同步两个数据库的脚本.数据库中有一个数据应该存储为树,所以我使用django-mptt作为新数据库.当我同步DB时,我从旧数据库中选择新数据,并将其保存在新数据库中.
我想知道是否有更好的方法将新节点添加到树中?现在看起来是下一个方式:
...
# Add new data to DB
for new_record in new_records:
# Find appropriate parent using data in 'new_record'
parent = get_parent(new_record)
# Create object which should be added using data in 'new_record'
new_node = MyMPTTModel(...)
new_node.insert_at(parent, save = True)
# Similar to:
# new_node.insert_at(parent, save = False)
# new_node.save()
Run Code Online (Sandbox Code Playgroud)
但它工作得很慢.我认为它以这种方式工作,因为每次调用该insert_at(..., save = True)方法后都django-mptt应该将新节点写入数据库并修改已经存在于数据库中的记录left和right键.
有没有办法在django-mptt每次调用时修改查询insert_at,然后在我打电话时将所有更改应用到一起save?或者你知道如何减少执行时间吗?
提前致谢.