FirmCiti Inc
FirmCiti Inc

Reputation: 407

how to have an integer along with ManytoMany field in django

So I am trying to finish up a recipe app, however storing my ingredients volume is a bit hard. eg: 3 - eggs, 1 butter, etc

I did my models like this:

class IngredientList(models.Model):
    name = models.CharField(max_length=100)
    recipes = models.ManyToManyField('RecipeList', through='ShoppingList')

    def __str__(self):
        return self.name


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

    def __str__(self):
        return self.name


class ShoppingList(models.Model):
    ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE)
    recipe = models.ForeignKey(RecipeList, on_delete=models.CASCADE)
    amount_needed = models.IntegerField(default=1)

if this is correct, how do I go forward with my views.py and outputing in my template?

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


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

and

{% for i in recipe %}
<div class="card col-sm-3 m-2 p-2">
    <img class="card-img-top img-fluid" src="https://www.seriouseats.com/recipes/images/2014/09/20140919-easy-italian-american-red-sauce-vicky-wasik-19-1500x1125.jpg ">
    <div class="card-body">
        <h4>{{ i.name}} <span class="badge badge-info">{{i.cuisine}}</span></h4>
        <p class="card-text">Ingredients: 
        {% for k in i.ingredients.all %}
        {{k}},
        {% endfor %}</p>
        <p class="card-text">Instructions: {{i.instructions}}</p>
        <p class="card-text">This makes {{ i.amount}} meals</p>
    </div>
</div>
{% endfor %}

but this only outputs the name of the ingredient, but i want to add the amount when saving the ingredients needed for recipe

Upvotes: 1

Views: 322

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

You can enumerate over the related ShoppingList models:

{% for k in i.shoppinglist_set.all %}
    {{ k.amount_needed }}  {{ k.ingredients }},
{% endfor %}

Upvotes: 1

Related Questions