I have a Menu model in which there is a parent field that refers to itself via a Foreign Key.
name = models.CharField(max_length=150)
parent = models.ForeignKey(
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.)