我有3种不同类型文章的3个查询集:右倾,中心,左倾。我试图将它们显示在3列中,因此它将显示为:
正确的精益|中心精益|左倾?
正确的精益|中心精益|左倾?
正确的精益|中心精益|左倾?
所以,我在三个查询集中都有这些,在视图中这样:
right_articles = sline.article_set.filter(avgLean__lte=-0.75).order_by('-credibility')[:25]
left_articles = sline.article_set.filter(avgLean__gte=0.75).order_by('-credibility')[:25]
center_articles = sline.article_set.filter(avgLean__gt=-0.75).filter(avgLean__lt=0.75).order_by('-credibility')[:25]
我在每个列中添加了一个计数器,作为上下文的一部分,如下所示:
return render(request, 'storylines/detail.html', {'n_articles': range(0, 24),
'storyline': sline,
'reqUser':request.user,
'vote':ini, 'right_articles':right_articles,
'left_articles': left_articles,
'center_articles': center_articles})
然后我转到模板并循环遍历这些:
<div class="row">
<div class= "col-4">
Left articles: {{ left_articles.count }}
</div>
<div class= "col-4">
Center articles: {{ center_articles.count }}
</div>
<div class= "col-4">
Right articles: {{ right_articles.count }}
</div>
</div>
{% for i in n_articles %}
<div class="row">
Trying {{ i }}<br>
{% with left_articles.i as lt_article %}
{% if lt_article %}
{% show_card lt_article %}
{% else %}
<div class="col-4">No Left article {{ i }}</div>
{% endif %}
{% endwith %}
{% with center_articles.i as cn_article %}
{% if cn_article %}
{% show_card cn_article %}
{% else %}
<div class="col-4">No Center article {{ i }}</div>
{% endif %}
{% endwith %}
{% with right_articles.i as rt_article %}
{% if rt_article %}
{% show_card rt_article %}
{% else %}
<div class="col-4">No Right article {{ i }}</div>
{% endif %}
{% endwith %}
</div>
{% endfor %}
第一行的计数语句显示我实际上每个左/中/右都有1个。如果我修改我的代码以用right_articles.0替换right_articles.i,我会得到一篇文章。说试试{{i}}的行显示我从0开始,所以当i = 0时,right_articles.i应该返回一篇文章。然而,不幸的是,我没有文章,这意味着我的语法有问题
{% with right_articles.i as rt_article %}
有谁能告诉我正确的方式来说出我在这里想说的话?
谢谢!
答案 0 :(得分:0)
我不建议改进任何内容,自定义标记过滤器可以解决这个问题:
const SurveyField = () => {
return <input />;
};
export default SurveyField;
现在,您将可以访问该项目
from django import template
register = template.Library()
@register.filter
def select_item(queryset,i):
return queryset[i]
# Be careful of IndexError: list index out of range