【问题标题】:.get_object() showing dataset rather than field data from model.get_object() 显示数据集而不是模型中的字段数据
【发布时间】:2019-11-12 16:00:42
【问题描述】:

我正在建立一个网站,在页面上显示食谱中的食谱。

这是我目前所拥有的

models.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)

views.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>

模板中{{指令}}变量的输出是:

<QuerySet [<recipesteps: name=Tomato cookbook=Cooking with tomato >, <recipesteps: name=Lettuce cookbook= Cooking with lettuce >]>

有没有一种方法可以在模板中的某个位置只显示成分的名称,并在另一个位置显示食谱而不显示?

【问题讨论】:

  • totalcontent 是什么,你在做totalcontent.objects.filter 但没有向我们展示那个模型?
  • 对不起,这应该是我从另一个问题复制的食谱步骤

标签: python django django-models django-templates


【解决方案1】:

如果你不想添加额外的上下文,你可以这样做:

<!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>

您的对象已经可以访问指令。

【讨论】:

    【解决方案2】:

    您必须遍历指令对象

    {% for instruction in instructions %}
       {{instruction.name}}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多