FirmCiti Inc
FirmCiti Inc

Reputation: 407

Display ManytoMany Django

trying to display all the ingredients that are associated to a recipe, however:

my models:

class IngredientList(models.Model):
    name = models.CharField(max_length=100)

class RecipeList(models.Model):
    name = models.CharField(max_length=100)
    ingredients = models.ManyToManyField('IngredientList')
    instructions = models.TextField(max_length=400)
    amount = models.IntegerField()

my views:

from django.shortcuts import render
from .models import IngredientList, RecipeList


def index(request):
    ing = RecipeList.objects.all()
    context = {'ing': ing}
    return render(request, 'myrecipes/home.html', context)

my template:

<div class="card-body">
        <h4>{{ details.name}} <span class="badge badge-info">{{details.cuisine}}</span></h4>
        <p class="card-text">Ingredients: {{details.ingredients}}</p>
        <p class="card-text">Instructions: {{details.instructions}}</p>
        <p class="card-text">This makes {{ details.amount}} meals</p>
    </div>

my output is "myrecipes.IngredientList.None"

Upvotes: 1

Views: 28

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

You need to access the queryset of the ingredients, so details.ingredients.all, furthermore you need to iterate over these ingredients, so you work with:

{% for ingredient in details.ingredients.all %}
    {{ ingredient }}
{% endfor %}

In the view you can load all the related Ingredients with one extra query with:

def index(request):
    ing = RecipeList.objects.prefetch_related('ingredients')
    return render(request, 'myrecipes/home.html', {'ing': ing})

This will avoid making an extra query per RecipeList.

Upvotes: 2

Related Questions