How to get all objects with their children using django orm?
I got very simple hierarchical structure: every object can have 0 or 1 parent. There's no limit on how many children each object can have.
So in my application I got such a model:
class O(Model):
name = CharField(max_length = 20)
parent = ForeignKey('O', related_n开发者_如何学Pythoname = 'children')
Now I would like to be able to fetch all objects who have a particular one Object1
in their parent-tree (as in their parent or parent of their parents, etc).
Should I use mptt or is there a simpler approach?
Yes, I suggest to use mppt. I like it.
There are a lot of usefull functions like instance.get_ancestors() or instance.get_children(). And many good and usfull template tags.
if you go with mptt I suggest reading the docs first. It's a nice implementation, and it's going to be the easiest in this case.
What you are looking for is named get_descendants() in mptt.
Be careful and use svn trunk, since the last release is not compatible with Django 1.0 and onwards. Hope this helps.
精彩评论