Friday, July 23, 2010

Re: Sorting list of related entities

On Jul 23, 12:25 pm, Jonhoo <j...@thesquareplanet.com> wrote:
> There is probably an easy answer to this, but I have been scratching
> my head for a while now: I have two models, Category and Program in a
> one-to-many relationship. I want to list all categories, and all
> programs within each category. I pass Category.objects.all() to the
> view, and in the view I run a for loop over the categories, and a
> second for loop over category.program_set.all in each category. The
> question is, how can I sort the output in that second for-loop?
>
> So, in code:
> views.py:
> def index(request):
>     return render_to_response ( 'list.html', { 'categories':
> Category.objects.select_related('program_set').all() } );
>
> list.html:
> {% for category in categories %}
>     ...
>     {{ category.name }}
>     {% for program in category.program_set.all %}
>         ...
>         {{ program.name }}
>         ...
>     {% endfor %}
> {% endfor %}
>
> How can I make the inner loop produce sorted output?
>
> Jon

You can't do this in the template. `program_set` acts like any other
queryset in that you can call `order_by` on it:

category.program_set.order_by('field1', 'field2')

but as you know, you can't pass arguments to functions in the template
language. If you always want to order by these fields, you can make
them the default on the Program model by setting the `ordering`
attribute of the inner Meta class. Otherwise, you could define a
simple template filter to do the ordering:

@register.filter
def order_by(qs, fields):
return qs.order_by(*fields.split(','))

and use it in the template:

{% for program in category.program_set.all|
order_by:"field1,field2" %}

--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment