简体   繁体   中英

Display relationship attribute in django template

So, in my models I have:

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,
    )

In my template:

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

How can I show the quantity atribute of the Recipe_Ingredient associated with this recipe and ingredient? In the shell I could do this query: Recipe_Ingredient.objects.get(ingredient=Ingredient.objects.get(name='Cenoura'), recipe=Recipe.objects.get(name='Teste')), but I'm not quite sure how to do it in the template and what's the correct way of doing it.

You can accomplish what you want by iterating over the Receipe_Ingredient relationship.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM