Matthew Calabresi
Matthew Calabresi

Reputation: 487

Is there a better way to construct variables to pass to a template?

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

Answers (2)

Daniel Roseman
Daniel Roseman

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

K Z
K Z

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

Related Questions