【发布时间】:2021-11-14 21:47:40
【问题描述】:
尝试在我想要所有字段的地方循环多对多关系。
我的模特:
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)
我的观点:
from .models import Recipe
def home(request):
recipe = Recipe.objects.all()
context = {
"title": "Home Page",
"recipe": recipe
}
return render(request, "home.html", context)
还有我的模板:
{%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%}
想要展示成分、数量以及与之相关的单位。除了我只得到“成分”标题
【问题讨论】:
标签: json python-3.x django