On 6 oct, 17:27, Paweł Roman <romapa...@googlemail.com> wrote:
> I have a model which has a tree-like structure (not exactly a FK on
> self but we can assume that's the case).
>
> I want to visualise this tree using all records from the db. It seems
> impossible to do with QuerySet, if I have say 100 records (100 nodes
> in the tree) and I try building the tree recursively django will
> execute a SELECT for each node so it will hit the db 100 times to
> build the tree.

(snip)

> Am I missing something? Iterating tree-like data structures seems
> something quite common problem and someone must have done it already
> with django.

Please not that it's in a no way a Django-specific problem, but a
limitation of the relational model (or at least of it's most common
implementation, ie SQL).

The most obvious way to implement a tree in the relational model,
wknown as "Adjacency list", is the use of a self-referential foreign
key pointing on the parent record. It's easy to implement, easy to
maintain, but as you noticed not really efficient when you want to
build the whole tree or a branch of it.

One of the known workaround is the "Modified Preorder Tree
Transversal" (AKA "nested Set") pattern (google for more on this -
there's a django implementation here http://code.google.com/p/django-mptt/),
which is mostly optimized for reading deeply nested trees, but is not
very efficient wrt/ insert/update.  So if your hierarchy is 1/ deeply
nested and 2/ read often, rarely updated, then it might be what your
looking for.

Another known solution is the "Materialized path" pattern, which is
not as good as MPTT for reading and not as bad for inserts/updates.
Here again, google is your friend.

FWIW, there's also a django utility app that provides a generic
implementation of these tree patterns with a same API:
https://tabo.pe/projects/django-treebeard/docs/tip/

HTH

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to