我有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 %}
第一行的count语句显示,实际上,每个左/中/右有一个。如果我修改代码以将right_articles.i替换为right_articles.0,我将得到一篇文章。尝试{{ i }}的行显示我从0开始,所以当i=0时,right_articles.i应该返回一篇文章。然而,不幸的是,我没有得到任何文章,这意味着我在
{% with right_articles.i as rt_article %}
有人能告诉我怎么说我想说的话吗?
谢谢!
发布于 2018-05-17 20:30:32
我不会建议任何需要改进的地方,使用自定义标记过滤器就可以做到这一点:
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
所以现在,您将可以访问该项目。
{% with left_articles|select_item:i as lt_article %}
{% endwith %}
https://stackoverflow.com/questions/50399228
复制相似问题