gpt4 book ai didi

django - 检测行差异( View 或模型)?

转载 作者:行者123 更新时间:2023-12-02 00:07:55 24 4
gpt4 key购买 nike

我想在我的网站上显示一个出版物列表;但是,我还想显示一个标题,说明在特定年份发布的每组出版物的年份。

所以我希望我的最终结果是这样的(我的声誉是 1 :( 我无法上传图片):

https://dl.dropboxusercontent.com/u/10752936/Screen%20Shot%202013-06-21%20at%206.00.15%20PM.png

我有一个包含三列的表格; id(主键)、title(文章标题)、date(发表日期)

在我的模板文件中;执行以下操作将在每篇文章之前打印标题:

{% for curr_pub in all_publications %}
<h1>{{ curr_pub.date.year }}</h1>
<li>{{ curr_pub.title }}</li>
{% endfor %}

我正在传递按 '-date' 排序的 all_publications,这意味着我可以比较当前行 curr_pub 的 year 与前一个并检查它是否不同;并相应地打印(或不打印)标题。但是,我似乎无法在模板中执行此操作。

由于我是 Django 和 Python 的新手,我不知道该怎么做,这就是我需要帮助的地方;我的想法如下:

1) 在 model (def is_it_first_publication(self):) 中添加一个返回 truefalse - 但我真的做不到:| - ...而且我不确定这是否是我需要做的!

2) 第二个是在 view 中执行 in,并将额外的变量传递给模板;这是一个示例(在这种情况下效果很好):

在 View 中:

def publications(request):
all_publications = Publications.objects.order_by('-date')

after_first_row_flag = False
f_year = 'Null'
list_of_ids_of_first_publications = []

for curr_pub in all_publications:
if after_first_row_flag:
if curr_pub.date.year != f_year:
list_of_ids_of_first_publications.append(curr_pub.id)
f_year = curr_pub.date.year
else:
# The year of first (or earliest) publication has to be added
#
list_of_ids_of_first_publications.append(curr_pub.id)
f_year = curr_pub.date.year
after_first_row_flag = True

template = loader.get_template('counters/publications.html')
context = RequestContext(request, {
'all_publications': all_publications,
'list_of_first_publications': list_of_ids_of_first_publications,
})

return HttpResponse(template.render(context))

在模板中:

    {% for curr_pub in all_publications %}
{% if curr_pub.id in list_of_first_publications %}
<h1> {{ curr_pub.date.year }} </h1>
{% endif %}
<li> Placeholder for [curr_pub.title] </li>
{% endfor %}

最佳答案

regroup 内置过滤器可以为您完成此操作,而无需在 View 中注释您的对象。正如文档所说,它有点复杂。

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

{% regroup all_publications by date.year as year_list %}
{% for year in year_list %}
<h1>{{ year.grouper }}</h1>
{% for publication in year.list %}
<li>{{ publication.title }}</li>
{% endfor %}
{% endfor %}

关于django - 检测行差异( View 或模型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com