0

我开始使用 ' 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 个具有树结构的对象。

4

0 回答 0