Getting full tree from a child nodes

220 views
Skip to first unread message

Sean Brant

unread,
Mar 19, 2011, 6:18:12 PM3/19/11
to django-mptt-dev
Say I have this tree:

1
---1.1
---1.2
------1.2.1
2
--2.1
3
---3.1
---3.1
4

Given nodes [1.1, 1.2.1, 2, 3.1, 3.2, 4] how would I get a tree view
like this:

** [x] are node i have, (x) should be filled in.

(1)
---[1.1]
---(1.2)
------[1.2.1]
[2]
(3)
---[3.1]
---[3.2]
[4]

In other words I have some children at various depths based on those
children I'd like to get a tree from parent back down to those
children.

Hope that makes sense. Thanks for any help you might offer.

Craig de Stigter

unread,
Mar 19, 2011, 7:22:49 PM3/19/11
to django-...@googlegroups.com
Hi Sean

I don't think this is directly supported by mptt. However I think you can do it in one (quite inefficient query) by using Q objects.

Something like this:
 
from django.db.models import Q
import operator
def get_tree_ancestors(nodes): 
    if not nodes:
        return Node.objects.none()
    filters = []
    for n in nodes:
        filters.append(Q(tree_id=n.tree_id, lft__lte=n.lft, rght__gte=n.rght))
    q = reduce(operator.or_, filters)
    return Node.objects.filter(q)

I don't know how efficient this is for your database but it should do the trick

HTH
Craig

Sean Brant

unread,
Mar 19, 2011, 7:43:00 PM3/19/11
to django-mptt-dev
Thanks, works perfectly!
Reply all
Reply to author
Forward
0 new messages