Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Forms More on Models Quiz Model

igsm '
igsm '
10,440 Points

Where does step.order come from?

Kenneth Love I do not understand, how do we access step.order in lambda function?

 def course_detail(request, pk):
    course = get_object_or_404(models.Course, pk=pk)
    steps = sorted(chain(course.text_set.all(), course.quiz_set.all()),
                   key=lambda step: step.order)
    return render(request, 'courses/course_detail.html', {
        'course': course,
        'steps': steps
        })

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

sorted()'s key argument can be a callable (function, effectively). We're using a lambda so we don't have to write out a whole new function or, in this case, use getattr. We're giving the lambda an argument named step and this argument will be filled in with whatever item sorted is currently looking at in the iterable (it reads through each element in the iterable and compares them to each other). We're making the lambda return the order attribute from each step.

In plainer English, what sorted is doing here is taking a big pile of steps and ordering them based on their order attribute.