检测行差异(视图或模型)?

时间:2013-06-21 23:01:00

标签: django

我想在我的网站上显示出版物清单;不过,我还想透露一个标题,说明在那一年发布的每套出版物的年份。

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

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

我有一个有三列的表; id (primary key), title (the title of the article), and date (the date of publications)

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

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

我正在通过all_publications排序'-date',这意味着我可以将当​​前行curr_pub与前一行进行比较,然后检查一下不同或不同;并相应地打印(或不打印)标题。但是,似乎我不能在模板中这样做。

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

1)在modeldef is_it_first_publication(self):)中添加一个返回truefalse的函数 - 但我真的无法做到这一点: - ......我不确定这是否是我需要做的事情!

2)第二个是在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 %}

3 个答案:

答案 0 :(得分:1)

我认为您需要regroup模板标记;

{% regroup all_publications by date as publication_groups %}
<ul>
{% for publication_group in publication_groups %}
    <li>{{ publication_group.grouper }}
    <ul>
        {% for publication in publication_group.list %}
          <li>{{ publication.title }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul> 

答案 1 :(得分:1)

也许模板标记regroup可以提供帮助。

或者,您可以在视图函数中按年份进行此分组(稍后将尝试提供代码)。

答案 2 :(得分:1)

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

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 %}