【发布时间】:2014-01-15 17:53:55
【问题描述】:
所以我有一个模板:
{% for Chapter in latest_chapter_list %}
{% ifequal Chapter.manga|truncatechars:20 Manga.name|truncatechars:20 %}
{{Chapter.chapter}}
{% endifequal %}
{% endfor %}
型号:
class Manga(models.Model):
name = models.CharField(max_length=20,help_text='Name of the comic/manga')
class Chapter(models.Model):
manga = models.ForeignKey(Manga)
chapter = models.IntegerField(default=1, help_text='Number of a chapter')
所以我想要的是模板只显示 5 个项目,而不是所有通过 if 的项目。在普通代码中,我会添加一个临时值来计算每次添加以及稍后的重置,但我是 django 的新手,我不知道如何处理这个问题。 我也无法弄清楚为什么我的 if 只有在我将两个名称都剪成相等长度时才有效,即使它们应该是相同的长度,不是吗?
还有我的看法:
def index(request):
latest_item_list = Manga.objects.all().order_by('-added_on')[:5]
latest_chapter_list = Chapter.objects.all().order_by('-chapter')
context = {'latest_item_list': latest_item_list,
'latest_chapter_list': latest_chapter_list
}
return render(request, 'Item/index.html', context)
任何帮助或提示将不胜感激!
编辑,解决方案:在视图中创建了新的过滤列表:
latest_chapter_list_short = Chapter.objects.filter(chapter__lt=6)
并遍历它而不是完整列表!
【问题讨论】:
标签: django django-models django-templates django-views