我正在与Django QuerySets斗争。这是我的数据库的JSON转储,包含数据:
[
{
"fields": {
"label_number": "1",
"label_type": "A",
"label_desc_nl": "NL Text",
"label_desc_en": "EN Text",
"label_desc_de": "DE Text",
"label_desc_pl": "PL Text",
"label_desc_es": "ES Text",
"label_desc_fr": "FR Text",
"label_desc_it": "IT Text",
"label_desc_pt": "PT Text",
"label_desc_cs": "CS Text"
},
"model": "myapp.labels",
"pk": 1
},
{
"fields": {
"label_number": "1",
"label_type": "B",
"label_desc_nl": "NL Text",
"label_desc_en": "EN Text",
"label_desc_de": "DE Text",
"label_desc_pl": "PL Text",
"label_desc_es": "ES Text",
"label_desc_fr": "FR Text",
"label_desc_it": "IT Text",
"label_desc_pt": "PT Text",
"label_desc_cs": "CS Text"
},
"model": "myapp.labels",
"pk": 2
}
]
所以,让我们说我想从" label_desc_fr"中获取数据。 WHERE label_number是1 AND label_type = B.我试图在我的视图中构建并执行QuerySet,如下所示:
q1 = labels.objects.filter(label_number="1")
q1 = q1.filter(label_type="B")
return render(request, 'frontend/base_home.html', {'q1' : q1})
页面加载没有错误。现在我尝试从我的模板中访问数据,如下所示:
{{q1.label_desc_fr}}
没有显示任何内容。 :(我搜索了一个查询集显示所有变量{{q1。?}}的方法,但我无法找到一种方法来实现这一点。在我看来,Django文档清楚地创建了QuerySets而不是如此变通从模板中检索它们。现在我想知道,如何在模板中检索结果?
谢谢你们!
答案 0 :(得分:1)
您的问题是您在模板中访问q1
,它是您的完整QuerySet,它不是单个对象。我认为这应该有效:
q1 = labels.objects.filter(label_number="1", label_type="B")
return render(request, 'frontend/base_home.html', {'q1' : q1})
然后在你的模板中:
{% for q in q1 %}
{{ q.label_desc_fr }}
{% endfor %}