简体   繁体   中英

model_mommy breaks django-mptt

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM