How do i query all the fields in a django Many to Many

  django, json, python-3.x

Trying to loop over a many to many relationship where I want all the fields.

My Models:

class Recipe(models.Model):

    title = models.CharField(max_length=200)
    slug = AutoSlugField(populate_from="title")
    category = models.ForeignKey(RecipeTopic, on_delete=models.CASCADE)
    image = models.ImageField()
    description = models.TextField()
    ingredients = models.ManyToManyField(Ingredient, through="IngredientList")
    directions = models.TextField()
    servings = models.IntegerField()
    time = models.IntegerField()
    cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE)

    def __str__(self):
        return self.title


class IngredientList(models.Model):
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    Recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    amount = models.FloatField(default=1)
    unit = models.ForeignKey(Units, on_delete=models.CASCADE)

My Views:

from .models import Recipe

def home(request):
    recipe = Recipe.objects.all()
    context = {
        "title": "Home Page",
        "recipe": recipe
    }
    return render(request, "home.html", context)

and my template:

    {%for r in recipe %}
        <h2>{{r.title}}</h2>
        <h4>Ingredients:</h4>
        {%for i in r.ingredients.all %}
           <p>---{{i.amount}}{{i.unit}}    {{i.ingredient}}</p>
        {%endfor%} 
{%endfor%}

Want to showcase the ingredients, their amount, and the units that goes along with them. Except that I am only getting the "ingredient" title

Source: Python-3x Questions

LEAVE A COMMENT