I have Menu
model which has ForeignKey named parent related with itself.
If parent is None it means this menu is parent menu if it shows another Menu object it means it is submenu for its parent(many-to-one relation)
Here is my problem, I want to get all menus with its submenus using prefetch_related
, How can I do it?
Note: I do not want to get submenus going database each time in for menu
Here is my model class
class Menu(models.Model):
title = models.CharField(max_length=30)
language = models.ForeignKey(Language)
parent = models.ForeignKey("self", default=None, blank=True,
null=True, related_name="submenus")
Here is my query
pm2 = Menu.objects.filter(parent=None, language__code=language, menutype=menutype)
.prefetch_related("submenus").order_by("order")
for p in pm2:
print(p.title)
print(p.submenus)
When I print the submenus the result is app.Menu.None
submenus
at all, so I would expect.prefetch_related("submenus")
to give an error. Will your submenus have their own submenus, or will your menus only have two levels? If you have multiple levels, then you may want to look at django-mptt. – Breathy