Python Django无法访问模型中的所有对象
我的观点是这样的:Python Django无法访问模型中的所有对象,python,django,object,model,Python,Django,Object,Model,我的观点是这样的: 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'] = Categor
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
当我在模板中尝试执行给定的上下文变量,如so{{category}
时,它会打印出[]
aka model name+它的标题,我假定标题会被打印出来,因为我在model.py中设置了\uuuunicode\uuuuuuuuo(self):返回self.title
,但我无法从给定对象访问任何其他字段category.id
和其他所有内容一样为空。如何访问这些内容?您的代码是:
context['category'] = Category.objects.all()
因此,它应该是:
context['categories'] = Category.objects.all()
在模板中:
{% for category in categories %}
{{ category.name }}
{% endfor %}
您在测试中获得的输出是有意义的:
[<Category: Something not so interesting>]
[]
它是一个只有一个条目的数组,这个条目是类类别的对象,它的字符串表示形式是“非…”您需要在类别上迭代,因为它是queryset。例如,在模板中,您可以
<ul>
{% for c in category %}
<li> {{ c }} </li>
{% endfor %}
</ul>
{类别%中的c为%0}
- {{c}}
{%endfor%}
模板中的类别
是queryset(对象列表),而不是单个对象。您需要将其迭代为
{%for c in category %}
{{c.id}} : {{ c.other_attribute }}
{%endfor%}