我需要表現出這樣的事情在我的模板:如何按日期按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日
請看看'collections.defaultdict',通過它你可以根據日期分組數據。 –
@AvinashRaj我像你說的那樣使用了collections.defaultdict,你可以檢查編輯過的問題嗎? – hectorlr22
@AvinashRaj只打印「6月12日」,但我不能遍歷 – hectorlr22