我想创建一个表,显示给定月份的所有日期,然后检查这一天是否在数据库中,如果它显示给定记录的必要数据现在我有一个循环用于显示月的所有天数:
def example_table(request,pk,month):
something = database.filter(name__pk=pk,date__month=month).all()
num_days = monthrange(2021, month)[1]
num_days = range(1,num_days+1)
context = locals()
在模板中我添加了这样的内容:
{%for time in num_days%}
{%for x in something%}
{%if x.day == time%}
table
{%endif%}
{%endfor%}
{%endfor%}
但是这个记录重复了x次。有人能给我一些建议吗?Should看起来像
1 data data data
2
3
4 data data data
...etc
试试这样做,
from itertools import groupby
def example_table(request,pk,month):
something = database.filter(name__pk=pk,date__month=month).order_by("date__day")
day_wise_data = {day: tuple(data) for day, data in groupby(something, key=lambda each: each.date.day)}
num_days = monthrange(2021, month)[1]
num_days = range(1,num_days+1)
day_wise_data = [day_wise_data.get(day, tuple()) for day in num_days]
context = {"day_wise_data": day_wise_data}
<tr>
<th>Day</th>
<th colspan="100%">Day Data</th>
</tr>
{%for data in day_wise_data%}
<tr>
<td>{{ forloop.counter + 1 }}</td>
{% for obj in data %}
<td> {{ obj.whatever }} </td>
{% endfor %}
</tr>
{%endfor%}