[Answered ]-How can I avoid duplicating django sql queries when recursing

1👍

You can try to do prefetch two or three levels, which will likely be sufficient:

@register.simple_tag
def draw_menu(slug):
    qs = Menu.objects.all()
    qs = qs.filter(slug=slug) if slug else qs.filter(parent=None)
    return qs.prefetch_related('kids__kids')

Recursively prefetching could be implemented in Django, the queryset will need some updates, but at the moment is not the case. It is actually an interesting case that is not covered (yet).

Leave a comment