0

我正在使用 django-mptt 0.4.2 并且我的一棵数据树有问题。

这是在 mysql 中看到的树;

mysql> select id, lft,rght,level from my_object where tree_id=30613;
+-------+-----+------+-------+
| id    | lft | rght | level |
+-------+-----+------+-------+
| 89919 |   1 |   10 |     0 | 
| 89924 |  10 |   11 |     1 | 
| 89930 |   6 |    9 |     1 | 
| 90401 |   2 |    5 |     1 | 
| 90406 |   3 |    4 |     2 | 
| 90407 |   7 |    8 |     2 | 
+-------+-----+------+-------+

在我的 Python shell 中,它看起来是一样的:

>>> obj = MyObject.objects.filter(tree_id=30613)
>>> for o in obj:
...     print "%5d %2d %2d %1d" % (o.id, o.lft, o.rght, o.level)
... 
89919  1 10 0
89924 10 11 1
89930  6  9 1
90401  2  5 1
90406  3  4 2
90407  7  8 2

问题是当我使用 django.mptt 中的 .get_descendants() 方法时:

>>> parent_node = MyObject.objects.get(id=89919)
>>> descendants = parent_node.get_descendants()
>>> for o in descendants:
...     print "%5d %2d %2d %1d" % (o.id, o.lft, o.rght, o.level)
... 
90401  2  5 1
90406  3  4 2
89930  6  9 1
90407  7  8 2


>>> print descendants.query # Formatted for readability
SELECT * FROM `my_obj` 
WHERE (
    `my_obj`.`lft` <= 9  
    AND `my_obj`.`lft` >= 2  
    AND `my_obj`.`tree_id` = 30613 
) ORDER BY `my_obj`.`tree_id` ASC, `my_obj`.`lft` ASC

为什么 django-mptt 不检索所有后代?

4

1 回答 1

2

树处于不准确状态:

parentnode:89919[left=1, right=10]不能包含childnode:89924[left=10, right=11]

您可以在查询中看到它,它正在搜索子节点left >= 2 (paren_left+1)<= 9 (parent_right-1)

您可能想要重建树以获得正确的结果。

move_to最近用过吗?看看这里的注释:move_to(target, position='first-child'),可能是相关的。

The same problem may arise with inset_at and it's due to fact that when using insert_at or move_to you supply a parent node that is updated in the database but not in memory, so you have to get a fresh copy of the parent after each one of these actions.

More info here:insert_node using last-child does not work correctly

于 2011-04-04T13:10:41.117 回答