2016-06-12 97 views
0

我需要表現出這樣的事情在我的模板:如何按日期按Django中的輸出進行分組?

6月11日

  • 數據1
  • 數據2

6月10日

  • 數據3
  • 數據4

我的觀點:

def Inicio(request): 
    g = Gastos.objects.all() 
    return render(request, 'principal/gastos.html', {'g': g}) 

我的模型:

class Gastos(models.Model): 
    ... 
    fecha = models.DateTimeField(auto_now_add=True, auto_now=False) 
    ... 

我需要組由從模型字段 「日期星」 的當天,和我不知道如何做到這一點。

編輯 我用collections.defaultdict:

我的觀點:

def Inicio(request): 
    g = Gastos.objects.all() 
    lista = defaultdict(list) 
    for gasto in g: 
     lista['%s %s' %(gasto.fecha.day, gasto.fecha.strftime("%B"))].append(gasto) 
    return render(request, 'principal/gastos.html', {'lista': lista}) 

如果我在Python Shell打印 「LISTA」:

defaultdict(<type 'list'>, {"12 June": [<Gastos: Gasolina>, <Gastos: mandado>], "13 June": [<Gastos: Ropa>]}) 

我得到了我想要,但問題出在模板上,我無法遍歷每個對象。

我的模板:在HTML

{% for dia in lista %} 
    <h3>{{dia}}</h3> 
    {% for g in dia.items %} 
     <li>{{g.producto}}</li> 
    {% endfor %} 
{% endfor %} 

結果(無數據):

6月12日

6月13日

+0

請看看'collections.defaultdict',通過它你可以根據日期分組數據。 –

+0

@AvinashRaj我像你說的那樣使用了collections.defaultdict,你可以檢查編輯過的問題嗎? – hectorlr22

+0

@AvinashRaj只打印「6月12日」,但我不能遍歷 – hectorlr22

回答

0

lista是一本字典,所以我們是免費的在字典上應用items函數獲得鑰匙,值對。所以代碼應該是這樣的,

{% for key, value in lista.items %} 
    <h3>{{key}}</h3> 
    {% for g in value %} 
     <li>{{g.producto}}</li> 
    {% endfor %} 
{% endfor %} 
+0

內的對象,只能通過字典鍵遍歷lista中的對象。 –

+0

我必須使用dict()函數將常規字典中的defaultdict()轉換爲模板,然後在模板中使用「for key,lista.iteritems中的值」,因爲我使用的是Python 2.7 ,非常感謝你;) – hectorlr22

+0

defaultdict obj已經是一個字典對象,你只需要用'iteritems'替換'items' –