Django templates - printing comma separated ManyToManyField, sorting results into list in dict?

I have a Django project to manage a list of journal articles. Basic Model Article . It has various fields for storing things, such as the title of the article, date of publication, topic, as well as a list of companies mentioned in the article. ( company is its own model).

I want a template that prints a list of articles sorted by category, as well as a list of the companies mentioned.

However, I face two problems.

First, the company field is the ManyToMany field. I am printing this successfully now using all iterable, thanks to this SO question =). (Curious, but where is this all iterable, documented in the Django documentation?)

enumeration of objects from ManyToManyField

However, I would like to print "," (comma, then space) after each item except the last item. Thus, the output will be:

 Joe Bob Company, Sarah Jane Company, Tool Company 

and not:

 Joe Bob Company, Sarah Jane Company, Tool Company, 

How do you achieve this with the Django template system?

Secondly, each Article has a CharField called category , which stores the category for the article. I would like articles sorted by category whenever possible. Therefore, I use QuerySet and get a good list of related articles in article_list. Then I use the regroup template tag to sort it into categories and print each.

 { 'tennis': ('article_4', 'article_5') 'cricket': ('article_2', 'article_3') 'ping pong': ('article_1') } 

However, I need to make sure my input list is sorted before passing it to regroup . My question is: is it better to use the dictsort tag dictsort to sort inside the template, or use the QuerySet order_by call instead?

And I guess it is better to use regroup instead of trying to code it myself in Python inside the view?

Cheers, Victor

+6
python django django-templates
source share
2 answers

first question

Use python like connection 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 tag template to sort this inside the template, or should I use QuerySet order_by instead?

I would use a QuerySet order_by. I like to do such things in the DB. Beacuse with a huge dataset you can use database indexes.

And I guess it is better to use rearrangement rather than trying to code it myself in Python inside the view?

regroup. It is directly better to use python's own functions.

+14
source share

Try forloop.last for your first question

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

All Articles