Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict? Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict? django django

Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict?


first question

Use the python like join filter

{{ article.company.all|join:", " }}

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join

second question

My question is, is it better to use the dictsort template-tag to sort this inside the template, or should I use QuerySet's order_by call instead?

I would use QuerySet's order_by. I like doing such stuff in DB. Beacuse with a huge dataset you could use database indexes.

And I assume it's better to use regroup, rather than trying to code this myself in Python inside the view?

regroup. It is defintly better to use python native functions.


Try forloop.last for your first question

{% for company in article.companys.all %}  {{company.name}}{% if not forloop.last %}, {% endif %}{% endfor %}