浏览多个关系Django

时间:2017-02-20 23:25:13

标签: python django

我需要获取给定菜单的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()

2 个答案:

答案 0 :(得分:0)

如果我记得你的身份,你可以通过这种方式获得nameqty

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而不是实例等。它只是一个标准的交叉关系查询。