mptt.models: 332 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/mptt/models.py

Stats: 0 executed, 322 missed, 10 excluded, 374 ignored

  1. import operator
  2. import warnings
  3. from django.db import models
  4. from django.db.models.base import ModelBase
  5. from django.db.models.query import Q
  6. from django.utils.translation import ugettext as _
  7. from mptt.fields import TreeForeignKey, TreeOneToOneField, TreeManyToManyField
  8. from mptt.managers import TreeManager
  9. from mptt.utils import _exists
  10. class MPTTOptions(object):
  11. """
  12. Options class for MPTT models. Use this as an inner class called ``MPTTMeta``::
  13. class MyModel(MPTTModel):
  14. class MPTTMeta:
  15. order_insertion_by = ['name']
  16. parent_attr = 'myparent'
  17. """
  18. order_insertion_by = []
  19. left_attr = 'lft'
  20. right_attr = 'rght'
  21. tree_id_attr = 'tree_id'
  22. level_attr = 'level'
  23. parent_attr = 'parent'
  24. # deprecated, don't use this
  25. tree_manager_attr = 'tree'
  26. def __init__(self, opts=None, **kwargs):
  27. # Override defaults with options provided
  28. if opts:
  29. opts = opts.__dict__.items()
  30. else:
  31. opts = []
  32. opts.extend(kwargs.items())
  33. if 'tree_manager_attr' in [opt[0] for opt in opts]:
  34. warnings.warn(
  35. _("`tree_manager_attr` is deprecated; just instantiate a TreeManager as a normal manager on your model"),
  36. DeprecationWarning
  37. )
  38. for key, value in opts:
  39. setattr(self, key, value)
  40. # Normalize order_insertion_by to a list
  41. if isinstance(self.order_insertion_by, basestring):
  42. self.order_insertion_by = [self.order_insertion_by]
  43. elif isinstance(self.order_insertion_by, tuple):
  44. self.order_insertion_by = list(self.order_insertion_by)
  45. elif self.order_insertion_by is None:
  46. self.order_insertion_by = []
  47. def __iter__(self):
  48. return iter([(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')])
  49. # Helper methods for accessing tree attributes on models.
  50. def get_raw_field_value(self, instance, field_name):
  51. """
  52. Gets the value of the given fieldname for the instance.
  53. This is not the same as getattr().
  54. This function will return IDs for foreignkeys etc, rather than doing
  55. a database query.
  56. """
  57. field = instance._meta.get_field(field_name)
  58. return field.value_from_object(instance)
  59. def set_raw_field_value(self, instance, field_name, value):
  60. """
  61. Sets the value of the given fieldname for the instance.
  62. This is not the same as setattr().
  63. This function requires an ID for a foreignkey (etc) rather than an instance.
  64. """
  65. field = instance._meta.get_field(field_name)
  66. setattr(instance, field.attname, value)
  67. def update_mptt_cached_fields(self, instance):
  68. """
  69. Caches (in an instance._mptt_cached_fields dict) the original values of:
  70. - parent pk
  71. - fields specified in order_insertion_by
  72. These are used in pre_save to determine if the relevant fields have changed,
  73. so that the MPTT fields need to be updated.
  74. """
  75. instance._mptt_cached_fields = {}
  76. field_names = [self.parent_attr]
  77. if self.order_insertion_by:
  78. field_names += self.order_insertion_by
  79. for field_name in field_names:
  80. instance._mptt_cached_fields[field_name] = self.get_raw_field_value(instance, field_name)
  81. def insertion_target_filters(self, instance, order_insertion_by):
  82. """
  83. Creates a filter which matches suitable right siblings for ``node``,
  84. where insertion should maintain ordering according to the list of
  85. fields in ``order_insertion_by``.
  86. For example, given an ``order_insertion_by`` of
  87. ``['field1', 'field2', 'field3']``, the resulting filter should
  88. correspond to the following SQL::
  89. field1 > %s
  90. OR (field1 = %s AND field2 > %s)
  91. OR (field1 = %s AND field2 = %s AND field3 > %s)
  92. """
  93. fields = []
  94. filters = []
  95. for field in order_insertion_by:
  96. value = getattr(instance, field)
  97. filters.append(reduce(operator.and_, [Q(**{f: v}) for f, v in fields] +
  98. [Q(**{'%s__gt' % field: value})]))
  99. fields.append((field, value))
  100. return reduce(operator.or_, filters)
  101. def get_ordered_insertion_target(self, node, parent):
  102. """
  103. Attempts to retrieve a suitable right sibling for ``node``
  104. underneath ``parent`` (which may be ``None`` in the case of root
  105. nodes) so that ordering by the fields specified by the node's class'
  106. ``order_insertion_by`` option is maintained.
  107. Returns ``None`` if no suitable sibling can be found.
  108. """
  109. right_sibling = None
  110. # Optimisation - if the parent doesn't have descendants,
  111. # the node will always be its last child.
  112. if parent is None or parent.get_descendant_count() > 0:
  113. opts = node._mptt_meta
  114. order_by = opts.order_insertion_by[:]
  115. filters = self.insertion_target_filters(node, order_by)
  116. if parent:
  117. filters = filters & Q(**{opts.parent_attr: parent})
  118. # Fall back on tree ordering if multiple child nodes have
  119. # the same values.
  120. order_by.append(opts.left_attr)
  121. else:
  122. filters = filters & Q(**{'%s__isnull' % opts.parent_attr: True})
  123. # Fall back on tree id ordering if multiple root nodes have
  124. # the same values.
  125. order_by.append(opts.tree_id_attr)
  126. queryset = node.__class__._tree_manager.filter(filters).order_by(*order_by)
  127. if node.pk:
  128. queryset = queryset.exclude(pk=node.pk)
  129. try:
  130. right_sibling = queryset[:1][0]
  131. except IndexError:
  132. # No suitable right sibling could be found
  133. pass
  134. return right_sibling
  135. class MPTTModelBase(ModelBase):
  136. """
  137. Metaclass for MPTT models
  138. """
  139. def __new__(meta, class_name, bases, class_dict):
  140. """
  141. Create subclasses of MPTTModel. This:
  142. - adds the MPTT fields to the class
  143. - adds a TreeManager to the model
  144. """
  145. MPTTMeta = class_dict.pop('MPTTMeta', None)
  146. if not MPTTMeta:
  147. class MPTTMeta:
  148. pass
  149. initial_options = set(dir(MPTTMeta))
  150. # extend MPTTMeta from base classes
  151. for base in bases:
  152. if hasattr(base, '_mptt_meta'):
  153. for (name, value) in base._mptt_meta:
  154. if name == 'tree_manager_attr':
  155. continue
  156. if name not in initial_options:
  157. setattr(MPTTMeta, name, value)
  158. class_dict['_mptt_meta'] = MPTTOptions(MPTTMeta)
  159. cls = super(MPTTModelBase, meta).__new__(meta, class_name, bases, class_dict)
  160. return meta.register(cls)
  161. @classmethod
  162. def register(meta, cls, **kwargs):
  163. """
  164. For the weird cases when you need to add tree-ness to an *existing*
  165. class. For other cases you should subclass MPTTModel instead of calling this.
  166. """
  167. if not issubclass(cls, models.Model):
  168. raise ValueError(_("register() expects a Django model class argument"))
  169. if not hasattr(cls, '_mptt_meta'):
  170. cls._mptt_meta = MPTTOptions(**kwargs)
  171. abstract = getattr(cls._meta, 'abstract', False)
  172. # For backwards compatibility with existing libraries, we copy the
  173. # _mptt_meta options into _meta.
  174. # This was removed in 0.5 but added back in 0.5.1 since it caused compatibility
  175. # issues with django-cms 2.2.0.
  176. # some discussion is here: https://github.com/divio/django-cms/issues/1079
  177. # This stuff is still documented as removed, and WILL be removed again in the next release.
  178. # All new code should use _mptt_meta rather than _meta for tree attributes.
  179. attrs = set(['left_attr', 'right_attr', 'tree_id_attr', 'level_attr', 'parent_attr',
  180. 'tree_manager_attr', 'order_insertion_by'])
  181. warned_attrs = set()
  182. class _MetaSubClass(cls._meta.__class__):
  183. def __getattr__(self, attr):
  184. if attr in attrs:
  185. if attr not in warned_attrs:
  186. warnings.warn(
  187. "%s._meta.%s is deprecated and will be removed in mptt 0.6"
  188. % (cls.__name__, attr),
  189. #don't use DeprecationWarning, that gets ignored by default
  190. UserWarning,
  191. )
  192. warned_attrs.add(attr)
  193. return getattr(cls._mptt_meta, attr)
  194. return super(_MetaSubClass, self).__getattr__(attr)
  195. cls._meta.__class__ = _MetaSubClass
  196. try:
  197. MPTTModel
  198. except NameError:
  199. # We're defining the base class right now, so don't do anything
  200. # We only want to add this stuff to the subclasses.
  201. # (Otherwise if field names are customized, we'll end up adding two
  202. # copies)
  203. pass
  204. else:
  205. if not issubclass(cls, MPTTModel):
  206. bases = list(cls.__bases__)
  207. # strip out bases that are strict superclasses of MPTTModel.
  208. # (i.e. Model, object)
  209. # this helps linearize the type hierarchy if possible
  210. for i in range(len(bases) - 1, -1, -1):
  211. if issubclass(MPTTModel, bases[i]):
  212. del bases[i]
  213. bases.insert(0, MPTTModel)
  214. cls.__bases__ = tuple(bases)
  215. for key in ('left_attr', 'right_attr', 'tree_id_attr', 'level_attr'):
  216. field_name = getattr(cls._mptt_meta, key)
  217. try:
  218. cls._meta.get_field(field_name)
  219. except models.FieldDoesNotExist:
  220. field = models.PositiveIntegerField(db_index=True, editable=False)
  221. field.contribute_to_class(cls, field_name)
  222. # Add a tree manager, if there isn't one already
  223. if not abstract:
  224. manager = getattr(cls, 'objects', None)
  225. if manager is None:
  226. manager = cls._default_manager._copy_to_model(cls)
  227. manager.contribute_to_class(cls, 'objects')
  228. elif manager.model != cls:
  229. # manager was inherited
  230. manager = manager._copy_to_model(cls)
  231. manager.contribute_to_class(cls, 'objects')
  232. if hasattr(manager, 'init_from_model'):
  233. manager.init_from_model(cls)
  234. # make sure we have a tree manager somewhere
  235. tree_manager = TreeManager()
  236. tree_manager.contribute_to_class(cls, '_tree_manager')
  237. tree_manager.init_from_model(cls)
  238. # avoid using ManagerDescriptor, so instances can refer to self._tree_manager
  239. setattr(cls, '_tree_manager', tree_manager)
  240. # for backwards compatibility, add .tree too (or whatever's in tree_manager_attr)
  241. tree_manager_attr = cls._mptt_meta.tree_manager_attr
  242. if tree_manager_attr != 'objects':
  243. another = getattr(cls, tree_manager_attr, None)
  244. if another is None:
  245. # wrap with a warning on first use
  246. from django.db.models.manager import ManagerDescriptor
  247. class _WarningDescriptor(ManagerDescriptor):
  248. def __init__(self, manager):
  249. self.manager = manager
  250. self.used = False
  251. def __get__(self, instance, type=None):
  252. if instance != None:
  253. raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
  254. if not self.used:
  255. warnings.warn(
  256. 'Implicit manager %s.%s will be removed in django-mptt 0.6. '
  257. ' Explicitly define a TreeManager() on your model to remove this warning.'
  258. % (cls.__name__, tree_manager_attr),
  259. DeprecationWarning
  260. )
  261. self.used = True
  262. return self.manager
  263. setattr(cls, tree_manager_attr, _WarningDescriptor(manager))
  264. elif hasattr(another, 'init_from_model'):
  265. another.init_from_model(cls)
  266. return cls
  267. class MPTTModel(models.Model):
  268. """
  269. Base class for tree models.
  270. """
  271. __metaclass__ = MPTTModelBase
  272. _default_manager = TreeManager()
  273. class Meta:
  274. abstract = True
  275. def __init__(self, *args, **kwargs):
  276. super(MPTTModel, self).__init__(*args, **kwargs)
  277. self._mptt_meta.update_mptt_cached_fields(self)
  278. def _mpttfield(self, fieldname):
  279. translated_fieldname = getattr(self._mptt_meta, '%s_attr' % fieldname)
  280. return getattr(self, translated_fieldname)
  281. def get_ancestors(self, ascending=False, include_self=False):
  282. """
  283. Creates a ``QuerySet`` containing the ancestors of this model
  284. instance.
  285. This defaults to being in descending order (root ancestor first,
  286. immediate parent last); passing ``True`` for the ``ascending``
  287. argument will reverse the ordering (immediate parent first, root
  288. ancestor last).
  289. If ``include_self`` is ``True``, the ``QuerySet`` will also
  290. include this model instance.
  291. """
  292. if self.is_root_node():
  293. if not include_self:
  294. return self._tree_manager.none()
  295. else:
  296. # Filter on pk for efficiency.
  297. return self._tree_manager.filter(pk=self.pk)
  298. opts = self._mptt_meta
  299. order_by = opts.left_attr
  300. if ascending:
  301. order_by = '-%s' % order_by
  302. left = getattr(self, opts.left_attr)
  303. right = getattr(self, opts.right_attr)
  304. if not include_self:
  305. left -= 1
  306. right += 1
  307. qs = self._tree_manager._mptt_filter(
  308. left__lte=left,
  309. right__gte=right,
  310. tree_id=self._mpttfield('tree_id'),
  311. )
  312. return qs.order_by(order_by)
  313. def get_children(self):
  314. """
  315. Returns a ``QuerySet`` containing the immediate children of this
  316. model instance, in tree order.
  317. The benefit of using this method over the reverse relation
  318. provided by the ORM to the instance's children is that a
  319. database query can be avoided in the case where the instance is
  320. a leaf node (it has no children).
  321. If called from a template where the tree has been walked by the
  322. ``cache_tree_children`` filter, no database query is required.
  323. """
  324. if hasattr(self, '_cached_children'):
  325. qs = self._tree_manager.filter(pk__in=[n.pk for n in self._cached_children])
  326. qs._result_cache = self._cached_children
  327. return qs
  328. else:
  329. if self.is_leaf_node():
  330. return self._tree_manager.none()
  331. return self._tree_manager._mptt_filter(parent=self)
  332. def get_descendants(self, include_self=False):
  333. """
  334. Creates a ``QuerySet`` containing descendants of this model
  335. instance, in tree order.
  336. If ``include_self`` is ``True``, the ``QuerySet`` will also
  337. include this model instance.
  338. """
  339. if self.is_leaf_node():
  340. if not include_self:
  341. return self._tree_manager.none()
  342. else:
  343. return self._tree_manager.filter(pk=self.pk)
  344. opts = self._mptt_meta
  345. left = getattr(self, opts.left_attr)
  346. right = getattr(self, opts.right_attr)
  347. if not include_self:
  348. left += 1
  349. right -= 1
  350. return self._tree_manager._mptt_filter(
  351. tree_id=self._mpttfield('tree_id'),
  352. left__gte=left,
  353. left__lte=right
  354. )
  355. def get_descendant_count(self):
  356. """
  357. Returns the number of descendants this model instance has.
  358. """
  359. if self._mpttfield('right') is None:
  360. # node not saved yet
  361. return 0
  362. else:
  363. return (self._mpttfield('right') - self._mpttfield('left') - 1) / 2
  364. def get_leafnodes(self, include_self=False):
  365. """
  366. Creates a ``QuerySet`` containing leafnodes of this model
  367. instance, in tree order.
  368. If ``include_self`` is ``True``, the ``QuerySet`` will also
  369. include this model instance (if it is a leaf node)
  370. """
  371. descendants = self.get_descendants(include_self=include_self)
  372. return self._tree_manager._mptt_filter(descendants,
  373. left=(models.F(self._mptt_meta.right_attr) - 1)
  374. )
  375. def get_next_sibling(self, **filters):
  376. """
  377. Returns this model instance's next sibling in the tree, or
  378. ``None`` if it doesn't have a next sibling.
  379. """
  380. qs = self._tree_manager.filter(**filters)
  381. if self.is_root_node():
  382. qs = self._tree_manager._mptt_filter(qs,
  383. parent__isnull=True,
  384. tree_id__gt=self._mpttfield('tree_id'),
  385. )
  386. else:
  387. qs = self._tree_manager._mptt_filter(qs,
  388. parent__id=getattr(self, '%s_id' % self._mptt_meta.parent_attr),
  389. left__gt=self._mpttfield('right'),
  390. )
  391. siblings = qs[:1]
  392. return siblings and siblings[0] or None
  393. def get_previous_sibling(self, **filters):
  394. """
  395. Returns this model instance's previous sibling in the tree, or
  396. ``None`` if it doesn't have a previous sibling.
  397. """
  398. opts = self._mptt_meta
  399. qs = self._tree_manager.filter(**filters)
  400. if self.is_root_node():
  401. qs = self._tree_manager._mptt_filter(qs,
  402. parent__isnull=True,
  403. tree_id__lt=self._mpttfield('tree_id'),
  404. )
  405. qs = qs.order_by('-%s' % opts.tree_id_attr)
  406. else:
  407. qs = self._tree_manager._mptt_filter(qs,
  408. parent__id=getattr(self, '%s_id' % opts.parent_attr),
  409. right__lt=self._mpttfield('left'),
  410. )
  411. qs = qs.order_by('-%s' % opts.right_attr)
  412. siblings = qs[:1]
  413. return siblings and siblings[0] or None
  414. def get_root(self):
  415. """
  416. Returns the root node of this model instance's tree.
  417. """
  418. if self.is_root_node() and type(self) == self._tree_manager.tree_model:
  419. return self
  420. return self._tree_manager._mptt_filter(
  421. tree_id=self._mpttfield('tree_id'),
  422. parent__isnull=True
  423. ).get()
  424. def get_siblings(self, include_self=False):
  425. """
  426. Creates a ``QuerySet`` containing siblings of this model
  427. instance. Root nodes are considered to be siblings of other root
  428. nodes.
  429. If ``include_self`` is ``True``, the ``QuerySet`` will also
  430. include this model instance.
  431. """
  432. if self.is_root_node():
  433. queryset = self._tree_manager._mptt_filter(parent__isnull=True)
  434. else:
  435. parent_id = getattr(self, '%s_id' % self._mptt_meta.parent_attr)
  436. queryset = self._tree_manager._mptt_filter(parent__id=parent_id)
  437. if not include_self:
  438. queryset = queryset.exclude(pk=self.pk)
  439. return queryset
  440. def get_level(self):
  441. """
  442. Returns the level of this node (distance from root)
  443. """
  444. return getattr(self, self._mptt_meta.level_attr)
  445. def insert_at(self, target, position='first-child', save=False, allow_existing_pk=False):
  446. """
  447. Convenience method for calling ``TreeManager.insert_node`` with this
  448. model instance.
  449. """
  450. self._tree_manager.insert_node(self, target, position, save, allow_existing_pk=allow_existing_pk)
  451. def is_child_node(self):
  452. """
  453. Returns ``True`` if this model instance is a child node, ``False``
  454. otherwise.
  455. """
  456. return not self.is_root_node()
  457. def is_leaf_node(self):
  458. """
  459. Returns ``True`` if this model instance is a leaf node (it has no
  460. children), ``False`` otherwise.
  461. """
  462. return not self.get_descendant_count()
  463. def is_root_node(self):
  464. """
  465. Returns ``True`` if this model instance is a root node,
  466. ``False`` otherwise.
  467. """
  468. return getattr(self, '%s_id' % self._mptt_meta.parent_attr) is None
  469. def is_descendant_of(self, other, include_self=False):
  470. """
  471. Returns ``True`` if this model is a descendant of the given node,
  472. ``False`` otherwise.
  473. If include_self is True, also returns True if the two nodes are the same node.
  474. """
  475. opts = self._mptt_meta
  476. if include_self and other.pk == self.pk:
  477. return True
  478. if getattr(self, opts.tree_id_attr) != getattr(other, opts.tree_id_attr):
  479. return False
  480. else:
  481. left = getattr(self, opts.left_attr)
  482. right = getattr(self, opts.right_attr)
  483. return left > getattr(other, opts.left_attr) and right < getattr(other, opts.right_attr)
  484. def is_ancestor_of(self, other, include_self=False):
  485. """
  486. Returns ``True`` if this model is an ancestor of the given node,
  487. ``False`` otherwise.
  488. If include_self is True, also returns True if the two nodes are the same node.
  489. """
  490. if include_self and other.pk == self.pk:
  491. return True
  492. return other.is_descendant_of(self)
  493. def move_to(self, target, position='first-child'):
  494. """
  495. Convenience method for calling ``TreeManager.move_node`` with this
  496. model instance.
  497. NOTE: This is a low-level method; it does NOT respect ``MPTTMeta.order_insertion_by``.
  498. In most cases you should just move the node yourself by setting node.parent.
  499. """
  500. self._tree_manager.move_node(self, target, position)
  501. def _is_saved(self, using=None):
  502. if not self.pk or self._mpttfield('tree_id') is None:
  503. return False
  504. opts = self._meta
  505. if opts.pk.rel is None:
  506. return True
  507. else:
  508. if not hasattr(self, '_mptt_saved'):
  509. manager = self.__class__._base_manager
  510. # NOTE we don't support django 1.1 anymore, so this is likely to get removed soon
  511. if hasattr(manager, 'using'):
  512. # multi db support was added in django 1.2
  513. manager = manager.using(using)
  514. self._mptt_saved = _exists(manager.filter(pk=self.pk))
  515. return self._mptt_saved
  516. def save(self, *args, **kwargs):
  517. """
  518. If this is a new node, sets tree fields up before it is inserted
  519. into the database, making room in the tree structure as neccessary,
  520. defaulting to making the new node the last child of its parent.
  521. It the node's left and right edge indicators already been set, we
  522. take this as indication that the node has already been set up for
  523. insertion, so its tree fields are left untouched.
  524. If this is an existing node and its parent has been changed,
  525. performs reparenting in the tree structure, defaulting to making the
  526. node the last child of its new parent.
  527. In either case, if the node's class has its ``order_insertion_by``
  528. tree option set, the node will be inserted or moved to the
  529. appropriate position to maintain ordering by the specified field.
  530. """
  531. opts = self._mptt_meta
  532. parent_id = opts.get_raw_field_value(self, opts.parent_attr)
  533. # determine whether this instance is already in the db
  534. force_update = kwargs.get('force_update', False)
  535. force_insert = kwargs.get('force_insert', False)
  536. if force_update or (not force_insert and self._is_saved(using=kwargs.get('using', None))):
  537. # it already exists, so do a move
  538. old_parent_id = self._mptt_cached_fields[opts.parent_attr]
  539. same_order = old_parent_id == parent_id
  540. if same_order and len(self._mptt_cached_fields) > 1:
  541. for field_name, old_value in self._mptt_cached_fields.items():
  542. if old_value != opts.get_raw_field_value(self, field_name):
  543. same_order = False
  544. break
  545. if not same_order:
  546. opts.set_raw_field_value(self, opts.parent_attr, old_parent_id)
  547. try:
  548. right_sibling = None
  549. if opts.order_insertion_by:
  550. right_sibling = opts.get_ordered_insertion_target(self, getattr(self, opts.parent_attr))
  551. if right_sibling:
  552. self.move_to(right_sibling, 'left')
  553. else:
  554. # Default movement
  555. if parent_id is None:
  556. root_nodes = self._tree_manager.root_nodes()
  557. try:
  558. rightmost_sibling = root_nodes.exclude(pk=self.pk).order_by('-%s' % opts.tree_id_attr)[0]
  559. self.move_to(rightmost_sibling, position='right')
  560. except IndexError:
  561. pass
  562. else:
  563. parent = getattr(self, opts.parent_attr)
  564. self.move_to(parent, position='last-child')
  565. finally:
  566. # Make sure the new parent is always
  567. # restored on the way out in case of errors.
  568. opts.set_raw_field_value(self, opts.parent_attr, parent_id)
  569. else:
  570. # new node, do an insert
  571. if (getattr(self, opts.left_attr) and getattr(self, opts.right_attr)):
  572. # This node has already been set up for insertion.
  573. pass
  574. else:
  575. parent = getattr(self, opts.parent_attr)
  576. right_sibling = None
  577. if opts.order_insertion_by:
  578. right_sibling = opts.get_ordered_insertion_target(self, parent)
  579. if right_sibling:
  580. self.insert_at(right_sibling, 'left', allow_existing_pk=True)
  581. if parent:
  582. # since we didn't insert into parent, we have to update parent.rght
  583. # here instead of in TreeManager.insert_node()
  584. right_shift = 2 * (self.get_descendant_count() + 1)
  585. self._tree_manager._post_insert_update_cached_parent_right(parent, right_shift)
  586. else:
  587. # Default insertion
  588. self.insert_at(parent, position='last-child', allow_existing_pk=True)
  589. super(MPTTModel, self).save(*args, **kwargs)
  590. self._mptt_saved = True
  591. opts.update_mptt_cached_fields(self)
  592. def delete(self, *args, **kwargs):
  593. tree_width = (self._mpttfield('right') -
  594. self._mpttfield('left') + 1)
  595. target_right = self._mpttfield('right')
  596. tree_id = self._mpttfield('tree_id')
  597. self._tree_manager._close_gap(tree_width, target_right, tree_id)
  598. super(MPTTModel, self).delete(*args, **kwargs)