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

时光总嘲笑我的痴心妄想 提交于 2019-12-03 12:54:43

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 %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!