4 ms·
I don't know if ActiveRecord is capable of doing this, but here is how to do it with Django ORM: in models.py: class Node(models.Model): parent =
by Walkman 12y ago
I don't know if ActiveRecord is capable of doing this, but here is how to do it with Django ORM:
in models.py:
class Node(models.Model):
parent = models.ForeignKey('self', related_name='children')
in the view:
nodes = Node.objects.prefetch_related('children')
in template:
{% for node in nodes %}
{% for subnode in node.children.all %}
...
{% endfor %}
{% endfor %}
This will make exactly two queries; one for all the parent nodes, and one for the children nodes. Django will make the pairing automagically, so you don't have to do it in view code.
- caust1c 12y agoUnfortunately, this still only gets the children of the root. If you want to be able to recursively get all the children and grandchildren of a root, you're going to be doing (N - leaves) queries where N is the number of Nodes in the tree. However, there is of course a django package to help with this and gathers all the nodes you care about into one query: https://github.com/django-mptt/django-mptt https://github.com/django-mptt/django-mptt
- herge 12y agoIf you ever need to deal with trees deeper than one level in django, I'd highly recommend looking at (as mentioned in another comment): https://www.djangopackages.com/packages/p/django-mptt/ https://www.djangopackages.com/packages/p/django-mptt/
- stephen_mcd 12y agoYou can easily render a tree many levels deep in O(n) time using a single DB query as an adjacency list with a lookup dictionary: http://blog.jupo.org/2010/01/26/linear-traversal-of-adjacency-list-trees/ http://blog.jupo.org/2010/01/26/linear-traversal-of-adjacenc... No need for mptt either.