在模型中选择Django中相关的多对多字段

时间:2018-01-14 18:30:38

标签: django

我的模型中有以下类:

class Dish(models.Model):
  name = models.CharField(max_length=200)

  def get_ingredients(self): 
    return #what to return?

class DishIngredient(models.Model):
  dish          = models.ForeignKey(Dish, on_delete=models.PROTECT)
  ingredient = models.ForeignKey(Ingredient, on_delete=models.PROTECT)
  number_of_units  = models.IntegerField('number of units')

class Ingredient(models.Model):
  name = models.CharField(max_length=100)
  unit = models.ForeignKey(Unit, on_delete=models.PROTECT)

我希望Dish.get_ingredients()返回一系列DishIngredient.number_of_units,Ingredient.name,Ingredient.unit

有人知道怎么做吗?

1 个答案:

答案 0 :(得分:2)

class Dish(models.Model):
    name = models.CharField(max_length=200)

    @property
    def get_ingredients(self):
         data = []
         dish_ingredients = DishIngredient.objects.filter(dish=self)
         for di in dish_ingredients:
            item = {
                    'number_of_units': di.number_of_units,
                    'name': di.ingredient.name,
                    'unit': di.ingredient.unit
                 }        
            data.append(item)
         return data