Search code examples
djangodjango-mptt

django_mptt model with post_save signal


class Category(MPTTModel):
    name = models.CharField(max_length=256)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

    class MPTTMeta:
        order_insertion_by = ['name']



@receiver(post_save)
def translate_name(sender, instance, created, **kwargs):
    if sender not in [Category]:
        return
    if created:
        # some operations with 'name_ru' 'name_en' fields (since django-modeltranslation)
        instance.save(update_fields=['name'])

raises "A node may not be made a child of any of its descendants"

node        <Category: Obj3>
right       3L
target      <Category: Obj2>
level       1L
self        <mptt.managers.TreeManager object at 0x108a76d10>
width       2L
new_tree_id 2L
tree_id     2L
position    u'last-child'
left        2L

When I exclude Category model from this post_save handler - everything works

Django==1.8.2
django-mptt==0.7.4

Any ideas or workaround ...


Solution

  •  def move_to(self, target, position='first-child'):
        """
        Convenience method for calling ``TreeManager.move_node`` with this
        model instance.
        NOTE: This is a low-level method; it does NOT respect
        ``MPTTMeta.order_insertion_by``.
        In most cases you should just move the node yourself by setting node.parent.
        """
    
    if instance.parent:
        instance.move_to(instance.parent)
    instance.save(update_fields=updated_field_list)