@@ -144,8 +144,40 @@ def mptt_before_update(mapper, connection, instance):
144144 table = mapper .mapped_table
145145 node_id = instance .id
146146
147+ mptt_move_inside = None
147148 left_sibling = None
148149 left_sibling_tree_id = None
150+ if hasattr (instance , 'mptt_move_inside' ):
151+ mptt_move_inside = instance .mptt_move_inside
152+ if hasattr (instance , 'mptt_move_before' ):
153+ (right_sibling_left ,
154+ right_sibling_right ,
155+ right_sibling_parent ,
156+ right_sibling_level ,
157+ right_sibling_tree_id ) = connection .execute (
158+ select ([table .c .lft , table .c .rgt , table .c .parent_id ,
159+ table .c .level , table .c .tree_id ]).
160+ where (table .c .id == instance .mptt_move_before )
161+ ).fetchone ()
162+ current_lvl_nodes = connection .execute (
163+ select ([table .c .lft , table .c .rgt , table .c .parent_id ,
164+ table .c .tree_id ]).
165+ where (and_ (table .c .level == right_sibling_level ,
166+ table .c .tree_id == right_sibling_tree_id ,
167+ table .c .lft < right_sibling_left ))
168+ ).fetchall ()
169+ if current_lvl_nodes :
170+ (left_sibling_left ,
171+ left_sibling_right ,
172+ left_sibling_parent ,
173+ left_sibling_tree_id ) = current_lvl_nodes [- 1 ]
174+ instance .parent_id = left_sibling_parent
175+ left_sibling = {'lft' : left_sibling_left , 'rgt' : left_sibling_right ,
176+ 'is_parent' : False }
177+ # if move_before to top level
178+ elif not right_sibling_parent :
179+ left_sibling_tree_id = right_sibling_tree_id - 1
180+
149181 # if placed after a particular node
150182 if hasattr (instance , 'mptt_move_after' ):
151183 (left_sibling_left ,
@@ -190,7 +222,13 @@ def mptt_before_update(mapper, connection, instance):
190222 ).fetchone ()
191223
192224 # if instance just update w/o move
193- if not left_sibling and str (node_parent_id ) == str (instance .parent_id ):
225+ if not left_sibling and str (node_parent_id ) == str (instance .parent_id ) and not mptt_move_inside :
226+ if left_sibling_tree_id is None :
227+ return
228+
229+ # fix tree shorting
230+ if instance .parent_id and not node_parent_id and node_tree_id == instance .tree_id :
231+ instance .parent_id = None
194232 return
195233
196234 # delete from old tree
@@ -226,7 +264,7 @@ def mptt_before_update(mapper, connection, instance):
226264 parent_tree_id , parent_level , node_level , left_sibling )
227265 else :
228266 # if insert after
229- if left_sibling_tree_id :
267+ if left_sibling_tree_id or left_sibling_tree_id == 0 :
230268 tree_id = left_sibling_tree_id + 1
231269 connection .execute (
232270 table .update (table .c .tree_id > left_sibling_tree_id )
0 commit comments