Python 在django模板中显示关系属性

Python 在django模板中显示关系属性,python,django,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): nam

因此,在我的模型中,我有:

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.components.all%中成分的百分比]
  • {{component.name}-#数量在这里
  • {%endfor%}
    如何显示与此配方和配料相关的配方配料的数量?
    在shell中,我可以执行以下查询:Recipe\u component.objects.get(component=component.objects.get(name='Cenoura'),Recipe=Recipe.objects.get(name='Teste'),但我不太确定如何在模板中执行此操作,以及正确的方法是什么。

    您可以通过迭代
    Receipe\u成分
    关系来完成所需的操作

    {% for recipe_ingredient in recipe.recipe_ingredient_set.all %}
        <li>{{ recipe_ingredient.ingredient.name }} -  {{ recipe_ingredient.quantity }} </li>
    {% endfor %}
    
    {recipe.recipe\u component\u set.all%}
    
  • {{recipe\u component.component.name}-{{recipe\u component.quantity}
  • {%endfor%}
    你能在你的问题中包括配方和成分模型吗?嗨@schillingt,我刚刚在我的问题中包括了它。有什么主意吗?太好了!非常感谢。