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.