Django模板中的显示关系属性

时间:2018-11-18 23:48:38

标签: python django

所以,在我的模型中,我有:

class Ingredient(models.Model):
    name = models.CharField(max_length=200)
    articleNumber = models.IntegerField(unique=True)
    costPerUnity = models.DecimalField(max_digits=4, decimal_places=2)

class Recipe(models.Model):
    name = models.CharField(max_length=200)
    ingredients = models.ManyToManyField(Ingredient, through='Recipe_Ingredient', related_name='recipes')

class Recipe_Ingredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    quantity = models.FloatField()

    GRAM = 'g'
    KILOGRAM = 'kg'
    LITER = 'l'
    CENTILITER = 'cl'

    UNITY_CHOICES = (
        (GRAM, 'Gram(s)'),
        (KILOGRAM, 'Kilogram(s)'),
        (LITER, 'Liter(s)'),
        (CENTILITER, 'Centiliter(s)'),
    )

    quantityUnit = models.CharField(
        max_length=2,
        choices=UNITY_CHOICES,
        default=GRAM,
    )

在我的模板中:

{% for ingredient in recipe.ingredients.all %}
    <li>{{ ingredient.name }} -  # quantity goes here </li>
{% endfor %}

如何显示与此配方和成分关联的Recipe_Ingredient的数量属性? 在外壳中,我可以执行以下查询:Recipe_Ingredient.objects.get(ingredient = Ingredient.objects.get(name ='Cenoura'),recipe = Recipe.objects.get(name ='Teste')),但是我不太确定如何在模板中执行此操作,以及执行此操作的正确方法是什么。

1 个答案:

答案 0 :(得分:1)

您可以通过遍历Receipe_Ingredient关系来完成所需的工作。

{% for recipe_ingredient in recipe.recipe_ingredient_set.all %}
    <li>{{ recipe_ingredient.ingredient.name }} -  {{ recipe_ingredient.quantity }} </li>
{% endfor %}