带有post_save信号的django_mptt模型

时间:2015-06-05 13:10:01

标签: django django-mptt

tst.jl

引发“某个节点可能不会成为其任何后代的孩子”

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'])

当我从这个post_save处理程序中排除Category模型时 - 一切正常

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

任何想法或解决方法......

1 个答案:

答案 0 :(得分:1)

 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)