Reputation: 487
Given a series of objects, I am trying to split them up into a nice, sorted, easy-to-display table view, which will serve as a generic (i.e. no dates) calendar.
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))
The variables are then iterated over with foreach
in the table columns in the template.
This seems really inelegant. Are my instincts correct?
Upvotes: 0
Views: 49
Reputation: 600049
I don't think you want seven lists at all. You should simply get all the objects for a user in one go, sorting by DOW and start hour:
WorkingHours.objects.filter(user_id=user_id).order_by('DOW', 'startHours')
and pass this to the template. There you can simply iterate through, perhaps using the ifchanged
or regroup
filters to output them in days.
Upvotes: 2
Reputation: 30483
You can consider using the following approach:
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))
Upvotes: 1