Is there any way to have Python expressions in a Django template?

For example, something simple that occurred to me in the polls example
(while following tutorial 4 in the results view) was to order the
choices by descending votes. I could see how to do this in the view by
injecting ordered_choices into the template context, but if I was
using a generic view this wouldn't be possible. I could add a
get_choice_list_by_popularity method to the model, and use

{% for choice in poll.get_choice_list_by_popularity %}

but it's fairly limited, and I could see myself needing a number of
methods that could be more easily used if they were more general.

Specifying sorting like this seems to be the kind of thing that should
go in the template, but

{% for choice in poll.get_choice_list(order_by=['-votes']) %}

doesn't work - obviously the for tag isn't expecting arbitrary
expressions, despite looking like the Python for loop.

Is there a better way to handle this kind of thing? Have you guys
found that you tend not to need this capability in the template
language in practice? Is this just a case where you wouldn't use a
generic view for the results display?

(Something that occurs to me is to use __getattr__ on the Poll class
to have 'virtual' methods that could sort by arbitrary attributes - I
guess this would work, but it's a bit magical, and potentially
error-prone.)

Thanks,
xtian

Reply via email to