0

给定一系列对象,我试图将它们拆分为一个漂亮的、排序的、易于显示的表格视图,该视图将用作通用(即无日期)日历。

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然后在模板的表列中迭代变量。

这看起来真的很不雅。我的直觉正确吗?

4

2 回答 2

2

我认为您根本不想要七个列表。您应该一次简单地获取用户的所有对象,按 DOW 和开始时间排序:

WorkingHours.objects.filter(user_id=user_id).order_by('DOW', 'startHours')

并将其传递给模板。在那里你可以简单地迭代,也许使用ifchangedorregroup过滤器在几天内输出它们。

于 2012-11-23T19:14:20.133 回答
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))
于 2012-11-23T17:48:58.250 回答