django-mptt order_insertion_by和树重建

时间:2014-01-23 08:06:21

标签: django django-mptt mptt

我开始使用'order_insertion_by'更改django-mptt中的默认排序。

到目前为止,我没有在我的本地发现问题,但我的测试失败了。

背景 我有测试夹具,可以在树形结构中创建大约10个对象和两棵树。

我在模型中添加了“order_insertion_by”。当我运行测试时,它失败了,因为树结构现在很乱。

但是如果我进行树重建,只需重新加载测试夹具后,树结构就可以了。

这是夹具tests.py

class TestPostCreationAndRetrival(LiveServerTestCase):

    headers = {'Accept': 'application/json; indent=4'}

    def fixture(self):
        self.school = Community.objects.create(name='TestSchool')
        self.school2 = Community.objects.create(name='NewTestschool')
        self.classroom1 = Community.objects.create(parent=self.school,
            name = 'Classroom1')
        self.classroom2 = Community.objects.create(parent=self.school,
            name = 'Classroom2')
        self.subclassroom1 = Community.objects.create(
            parent=self.classroom1,
            name='Subclassroom1')
        self.subclassroom2 = Community.objects.create(
            parent=self.classroom2,
            name='Subclassroom2')
        self.subclassroom3 = Community.objects.create(
            parent=self.classroom1,
            name='Subclassroom3')
        self.subclassroom4 = Community.objects.create(
            parent=self.classroom2,
            name='Subclassroom4')

        self.gou1 = Community.objects.create(
            parent=self.subclassroom1,
            name='GOC1')
        self.gou2 = Community.objects.create(
            parent=self.subclassroom2,
            name='GOC2')

def setUp(self):
    self.fixture()
    # This prints empty qs [] while I gave children in above fixture.
    print Community.objects.get(name='TestSchool').get_descendants()
    # Let's rebuild the tree
    Community.tree.rebuild()
    print Community.objects.get(name='TestSchool').get_descendants()
    # prints all the descendants just fine.

models.py

class Community(MPTTModel):
    tree = TreeManager()
    parent = models.ForeignKey('self', verbose_name=_(u'Parent'),
        null=True, blank=True, related_name='children')

    name = models.CharField(verbose_name=_(u'Name'),
        max_length=100)
    slug = models.SlugField(verbose_name=_(u'Slug'),
        max_length=100)

    objects = CommunityManager()

   class MPTTMeta:
       order_insertion_by = ['name']

这引发了一些问题:

  1. 我认为' order_insertion_by '强制在创建/更新对象时更新/重建树。但这并不一致,您必须在模型创建/更新后重建,以确保树处于良好状态。是这样吗?

  2. 在我的测试用例中,为什么最初的树乱了?我只创建了大约10个具有树形结构的对象。

0 个答案:

没有答案