鉴于一系列对象,我试图将它们分成一个漂亮,有序,易于显示的表格视图,该视图将作为通用(即无日期)日历。
def view_working_hours(request, user_id):
"""
Shows the working hours for a certain user.
This generates seven sorted lists which are then passed to the generic template
"""
wh0 = list(WorkingHours.objects.filter(user__id=user_id, DOW=0))
wh1 = list(WorkingHours.objects.filter(user__id=user_id, DOW=1))
wh2 = list(WorkingHours.objects.filter(user__id=user_id, DOW=2))
wh3 = list(WorkingHours.objects.filter(user__id=user_id, DOW=3))
wh4 = list(WorkingHours.objects.filter(user__id=user_id, DOW=4))
wh5 = list(WorkingHours.objects.filter(user__id=user_id, DOW=5))
wh6 = list(WorkingHours.objects.filter(user__id=user_id, DOW=6))
wh0.sort(key = lambda x: x.startHours)
wh1.sort(key = lambda x: x.startHours)
wh2.sort(key = lambda x: x.startHours)
wh3.sort(key = lambda x: x.startHours)
wh4.sort(key = lambda x: x.startHours)
wh5.sort(key = lambda x: x.startHours)
wh6.sort(key = lambda x: x.startHours)
return render_to_response('homesite/show_schedule.html',
{'wh0': wh0, 'wh1': wh1, 'wh2': wh2, 'wh3': wh3, 'wh4': wh4, 'wh5': wh5, 'wh6': wh6,},
context_instance=RequestContext(request))
然后在模板的表格列中使用foreach
迭代变量。
这看起来真的很不优雅。我的直觉是否正确?
答案 0 :(得分:2)
我认为你根本不想要七个名单。您应该只需一次获取用户的所有对象,按DOW排序并开始小时:
WorkingHours.objects.filter(user_id=user_id).order_by('DOW', 'startHours')
答案 1 :(得分:1)
您可以考虑使用以下方法:
def view_working_hours(request, user_id):
"""
Shows the working hours for a certain user.
This generates seven sorted lists which are then passed to the generic template
"""
result = {}
for i in xrange(7):
result["wh"+str(i)] = sorted(
list(WorkingHours.objects.filter(user__id=user_id, DOW=i)),
key=lambda x:x.startHours)
return render_to_response('homesite/show_schedule.html', result,
context_instance=RequestContext(request))