我的观点如下:
class PageView(DetailView):
queryset = Page.objects.all()
template_name = 'page.html'
def get_context_data(self, **kwargs):
context = super(PageView, self).get_context_data(**kwargs)
context['category'] = Category.objects.all()
context['categoryitem'] = CategoryItem.objects.all()
return context
在模板中,我尝试执行给定的上下文变量,如下所示 {{ category }}
它打印出 [<Category: Something not so interesting>]
又名模型名称+它的标题,我认为标题被打印出来,因为我设置了 __unicode__(self): return self.title
在 model.py 中,但我无法访问给定对象中的任何其他字段。 category.id
和其他一切一样都是空白的。我如何访问这些内容?
最佳答案
您的代码是:
context['category'] = Category.objects.all()
所以应该是:
context['categories'] = Category.objects.all()
在你的模板中:
{% for category in categories %}
{{ category.name }}
{% endfor %}
您在测试中得到的输出是有意义的:
[<Category: Something not so interesting>]
这是一个只有一个条目的数组,该条目是 Category 类的一个对象,它的字符串表示形式是“Something not ...”
关于python - Django 无法访问模型中的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395892/