Recursion for 1 database query

I have a Menu model in which there is a parent field that refers to itself via a Foreign Key.

class Menu(models.Model):
    name = models.CharField(max_length=150)
    parent = models.ForeignKey(
    def __str__(self):

I get menu_name through the URL, and then pull a specific instance of Menu.objects.get(name=menu_name) from the database.
I need to output all parents from the Menu object, as well as child. This requires only 1 DB request. I have already tried both select and prefetch and the Prefetch method. I don’t understand how to implement this. help pls

This is actually not the best way to model hierarchical data within a relational database.

Your optimal solution is going to depend upon whether it’s only going to be two levels or if you’re looking at a multi-level menu structure.

If it’s just two levels, then you’re usually going to be better off with two separate tables. (In the general case, the two levels of menu are two different entities with two different behaviors. The root menu entries exist only to cause the submenu to be displayed, while the child menus are links to the target pages.)

If you have a multi-level menu, see the message and referenced links at Some modelling advice - #12 by KenWhitesell for some ideas of generalized ways to model hierarchical data in a relational database.

1 Like

That is, such code is not very good? Here I can only get “children” in hierarchical order, and no parents.