Django&;Python:创建时间表
我正在尝试使用Django创建一个时间表。我试图用Python实现它,它看起来像:Django&;Python:创建时间表,python,django,Python,Django,我正在尝试使用Django创建一个时间表。我试图用Python实现它,它看起来像: durations = [30, 30, 45] #lessons with various durations count=0 start_time = 9 for x in durations: count = count + x/60 end_time = count + start_time print(end_time) 输出: 9.5 # 09:30 10.0 # 10
durations = [30, 30, 45] #lessons with various durations
count=0
start_time = 9
for x in durations:
count = count + x/60
end_time = count + start_time
print(end_time)
输出:
9.5 # 09:30
10.0 # 10:00
10.75 # 10.45
我的Django模板:
{% for student in students %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{ student.first_name }} {{ student.last_name }}</td>
<td>{{ student.duration }} mins</td>
<! Stuck here: start time and end time ––>
<td>Start Time - End Time</td>
</tr>
{% endfor %}
有一些过滤器可以做一些数学运算,比如“加法”和“sub”,但似乎我们不能做“x=x+1”之类的事情
有什么想法吗?非常感谢 您应该在视图中进行计算,而不是在模板中进行计算。下面是一个可以使用的pythonic解决方案(请参阅代码注释以获取解释):
#查看
从datetime导入datetime,timedelta
定义您的_视图(请求):
students=list(Student.objects.all())#数据库只命中一次
计数=0
开始时间=datetime.now().replace(小时=9,秒=0,微秒=0,分钟=0)#开始时间为上午9点
对于学生中的s:#由于查询已被评估,因此不再有DB命中
s、 start=start_time.strftime(“%H:%M”)#使用strftime从datetime对象获取字符串
开始时间+=时间增量(分钟=持续时间)#添加持续时间的时间增量以增加开始时间
s、 end=start\u time.strftime(“%H:%M”)
返回呈现(请求'template.html',{'students':students})
#模板
{学生百分比中的学生百分比}
{{forloop.counter}
{{student.first_name}{{student.last_name}}
{{student.duration}}分钟
{{student.start}-{{student.end}
{%endfor%}
如何在django中存储持续时间
?它们是整数吗?好的。我认为最好的方法是使用自定义模板标记;如果你添加与你的学生
模型相关的代码,我可以帮你。@PedramParsian谢谢你的帮助,我刚刚得到这个时间表。想知道你是否想看一看吗?非常感谢!我现在尝试添加几个休息时间(固定时间,例如12:00到12:30和14:00到14:45)。我想在“学生中的s”之外再做几个“for循环”,但我想你们一定有更聪明的解决方案吧?我将编辑我的问题以了解详细信息。再次感谢!如果你问一个新问题会更好:)。另外,如果你想让我看看这个问题,那么请在下面的评论部分提供参考:)。非常感谢你在“views.py”上的帮助。想知道你是否想看一看?
Student A | 30 mins | 09:00 - 09:30
Student B | 30 mins | 09:30 - 10:00
Student C | 45 mins | 10:00 - 10:45
# view
from datetime import datetime, timedelta
def your_view(request):
students = list(Student.objects.all()) # DB hit once only
count=0
start_time = datetime.now().replace(hour=9,second=0,microsecond=0,minute=0) # getting start time at 9 am
for s in students: # no more DB hits as query is already evaluated
s.start = start_time.strftime('%H:%M') # using strftime to get string from datetime object
start_time += timedelta(minutes=s.duration) # adding timedelta of duration to increase start time
s.end = start_time.strftime('%H:%M')
return render(request, 'template.html', {'students':students})
# template
{% for student in students %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{ student.first_name }} {{ student.last_name }}</td>
<td>{{ student.duration }} mins</td>
<td>{{ student.start }} - {{ student.end }}</td>
</tr>
{% endfor %}