2013-06-21 32 views
3

我想在我的網站上顯示出版物清單;不過,我還想在這個特定的年份發表一篇標題,說明每一套出版物的年份。檢測行差異(視圖或模型)?

所以我想爲我的最終結果是這樣的(我的名聲是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 %} 

回答

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

三個答案提示重組貼對方的一分鐘之內。尼斯。 –

+0

現在一個爲接受答案而死亡的戰鬥;) –

+0

我會upvote所有和接受彼得的答案:) - 因爲他沒有忘記年'date.year'而不是'date' = P - 那麼將分組子組也被排序('-date')? – Thuglife

1

也許模板標籤regroup可以提供幫助。

或者,您可以在視圖函數中按年份分組(以後會嘗試提供代碼)。