I'm using model_mommy
to create instances of an MPTTModel
in my tests, but it seems like it breaks the tree managed by mptt:
>>> parent = mommy.make(Category)
>>> child = mommy.make(Category, parent=parent)
>>> parent.get_descendants()
[]
The same without using model_mommy works properly:
>>> parent = Category(name=u'Parent')
>>> parent.save()
>>> child = Category(name=u'Child', parent=parent)
>>> child.save()
>>> parent.get_descendants()
[<Category: Child>]
I suspect that the issue is that model_mommy provides random values for tree_id
, lft
, rght
and level
, which are mandatory fields, but should be handled by MPTT.
Is there a way to tell model mommy to not fill these fields at all ? Or is there a default value for these fields that would not break MPTT's save algorithm ?
Turns out that if lft
or rght
have a truthy value, MPTTModel.save
considers the node to already have been set up. Thus setting these fields to None
is enough to fix the tree update.
I created a mommy recipe that I use everywhere in my tests, so I don't have to remember to set these fields:
category_recipe = Recipe(Category, lft=None, rght=None)
And then in the test cases: category_recipe.make()
instead of mommy.make(Category)
.