2010-09-10 210 views
3

我有一個「模板」中呈現的「promotion」事件的queryset。這些促銷活動中的每一個還有一個或多個約會。我想要做的是顯示第一次和最後一次約會的日期。「Last」標記不起作用

到目前爲止,使用「第一」標籤的作品。然而,使用「最後一個」標籤的原因:

TemplateSyntaxError異常值: 捕獲的異常而呈現:不支持 負索引。

這裏是模板腳本

{% for promotion in promotions%} 
    {% with promotion.appointment_set.all as appointments %} 
     {% with appointments|first as first_ap %} 
      {{ first_ap.date|date }} 
     {% endwith %} 

     {% with appointments|last as last_ap %} 
      {{ last_ap.date|date }} 
     {% endwith %} 
    {% endwith %} 
{% endfor %} 

我在做什麼錯在這裏?

回答

2

last標記通過使用負索引格式對列表進行切片以獲得最後一個項目:collection[-1]。但是,如錯誤消息指出的那樣,查詢集不支持負向索引。

可能解決這個最簡單的方法是在你的Promotion模型創建一個新的方法來返回最後一個約會:

class Promotion(models.Model): 
    ... fields, etc ... 

    def get_last_appointment(self): 
     try: 
      return self.appointment_set.all().order_by('-date')[0] 
     except IndexError: 
      pass 

,並從模板稱之爲:

{{ promotion.get_last_appointment.date|date }} 
+0

謝謝丹尼爾。我實際上可能會使用這個,因爲我需要應用程序中其他地方的功能。但是,是的,我可以看到我可能會在其他地方使用Manoj的建議。 – alj 2010-09-10 15:34:56

3

原因你的問題是什麼@丹尼爾pointed out:查詢集不支持負向索引。他的解決方案值得探索。

解決這個問題的另一種方法是添加一個自定義過濾器,它將與列表和查詢集一起工作。喜歡的東西:

@register.filter 
def custom_last(value): 
    last = None 

    try: 
     last = value[-1] 
    except AssertionError: 
     try: 
      last = value.reverse()[0] 
     except IndexError: 
      pass 

    return last 

而且在模板:

{% with appointments|custom_last as last_ap %} 
+0

+1。這很好。 – 2010-09-10 14:39:53

+0

感謝這個Manoj。我認爲丹尼爾和丹尼爾都是很好的解決方案。 – alj 2010-09-10 15:31:58

5

的查詢集轉換成一個列表給它的模板還可以讓你之前,你想去的地方:

return render_to_response(template, { 
    appointments: list(Appointments.objects.all()) 
}) 

由於我在使用整個列表,我做了這樣的事情(可能有待改進):

{% for ap in appointments %} 
    {% ifequal ap appointments|last %} 
    ap.date 
    {% endifequal %} 
{% endfor %} 

對象屬性仍然有效。例如:ap.user.full_name