我需要获取给定菜单的Items name和qty列表。我如何查询并返回带有所需列的QuerySet。?
我只获得菜单列表但仍无法获得数量。我应该做多个查询或尝试使用原始SQL
class Item(models.Model):
name = models.CharField(max_length=20)
class Meals(models.Model):
name = models.CharField(max_length=50)
ingredients = models.ManyToManyField(Item, through='MealRecipe')
class Menu(models.Model):
name = models.CharField(max_length=50)
meals = models.ManyToManyField(Meals,through='CompMenu')
class CompMenu(models.Model):
TYPE_COMP = (
('B', 'Breakfast'),
('L', 'Lunch'),
('D', 'Dinner')
)
menu = models.ForeignKey(Menu)
meal = models.ForeignKey(Meals)
type = models.CharField(max_length=1, choices=TYPE_COMP)
class MealRecipe(models.Model):
meal = models.ForeignKey(Meal)
item = models.ForeignKey(Item)
qty = models.IntegerField()
答案 0 :(得分:0)
如果我记得你的身份,你可以通过这种方式获得name
和qty
:
menu = Menu.objects.filter(name='some_name')
meals_of_menu = menu[idx].meals.all()
receipes = MealRecipe.objects.filter(meal__in=meals_of_menu)
for receipe in receipes:
name = receipe.item.name
qty = receipe.qty
答案 1 :(得分:0)
MealRecipe.objects.filter(meal__menu=some_menu_instance).distinct()
应该这样做。或meal__menu__id=some_id
如果您有菜单ID而不是实例等。它只是一个标准的交叉关系查询。