python - .get_object() 显示数据集而不是模型中的字段数据
问题描述
我正在建立一个网站,在页面上显示食谱中的食谱。
这是我到目前为止所拥有的
模型.py
class cookbook(models.Model):
title = models.CharField(max_length=255,unique=True)
class ingredient (models.Model):
name = models.CharField(max_length=255,unique=True)
class recipesteps(models.Model):
ingredient = models.ForeignKey(ingredient,on_delete=models.CASCADE)
instructions = models.TextField()
time = models.IntegerField(default=0)
class recipe(models.Model):
name = models.CharField(max_length=255,unique=True)
cookbook = models.ForeignKey(cookbook,on_delete=models.CASCADE)
ingredient_used = models.ManyToManyField(ingredient)
recipe_steps = models.ForeignKey(recipesteps,on_delete=models.CASCADE)
def __str__(self):
return 'name={} cookbook={} `'.format(self.name,self.cookbook)
视图.py
from django.views.generic import DetailView
class RecipeDetailView(DetailView):
model = recipe
def get_context_data(self, **kwargs):
context = super(RecipeDetailView, self).get_context_data(**kwargs)
context['instructions'] = recipesteps.objects.filter(recipe=self.get_object())
return context
模板.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>{{ object.cookbook }}</h2>
<h2> Recipe Name = {{ object.name }} </h2>
<h2> Steps To Make:</h2>
{{ instructions }}
</body>
</html>
模板中 {{ instructions }} 变量的输出是:
<QuerySet [<recipesteps: name=Tomato cookbook=Cooking with tomato >, <recipesteps: name=Lettuce cookbook= Cooking with lettuce >]>
有没有一种方法可以在模板中的某一点只显示成分的名称,并在另一点显示食谱而没有?
解决方案
如果您不想添加额外的上下文,您可以这样做:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>{{ object.cookbook }}</h2>
<h2> Recipe Name = {{ object.name }} </h2>
<h2> Steps To Make:</h2>
{% for instruction in object.instructions.all %}
{{instruction.name}}
{% endfor %}
</body>
</html>
您的对象已经可以访问指令。
推荐阅读
- python-3.x - BeautifulSoup 无法读取 wiki 页面
- sql - 用子查询求和减去计数抛出错误
- php - 我想要“每当我点击饼图切片时,它应该将值传递到另一个页面”。我如何在 laravel 5.5 中使用 Lavacharts 来实现这一点?
- java - Java 错误中的 gas * price + value 资金不足
- javascript - 这个javascript返回语句是什么意思?
- xcode - Xcode scn 文件不显示
- sql - Liquibase 与 PostgreSQL:它不创建函数
- html - *ngIf... 当数据为空时,为 mat-checkbox 设置 disabled=true
- html - “与周围内容的偏移”是什么意思?
- javascript - 如何在leaflet.js中的标记上添加点击事件