Issue
i want to buld a menuCard, with categories and food. It should be possible to create multiple menusCards.
#My Try
How can i display the name of the MenuCard, the MenuCardCategories and the associated MenuCardFood in the .html document with jinja2? The result should look like this...
#first menuCard
menuCardName
menuCardCategoryName
foodName
foodName
foodName
menuCardCategoryName
foodName
foodName
foodName
#second menuCard
menuCardName
menuCardCategoryName
foodName
foodName
Solution
You need to query the MenuCard
objects and group the related MenuCardFood
items by their category. Possible soltuion would be:
objects_list = []
for menu in MenuCard.objects.all():
menu_context = {'menu': menu, 'categories': []}
categories = menu.menuCard_menuCardFood.values('menuCardCategories').distinct()
for category in categories:
category_context = {'category': category}
related_food_list = menu.menuCard_menuCardFood.filter(menuCardCategories=category)
category_context.update({'food_list': related_food_list})
menu_context['categories'].append(category_context)
objects_list.append(menu_context)
The above code should generate:
[
{"menu": MenuCardObject1, "categories": ["category": MenuCardCategoryObject, "food_list": <QuerySet of MenuCardFood objects>],
{"menu": MenuCardObject2, "categories": ["category": MenuCardCategoryObject, "food_list": <QuerySet of MenuCardFood objects>],
{"menu": MenuCardObject3, "categories": ["category": MenuCardCategoryObject, "food_list": <QuerySet of MenuCardFood objects>],
]
Answered By - Ersain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.