Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Django project for managing a list of journal articles. The main model is Article. This has various fields to store things like title of the article, publication date, subject, as well as list of companies mentioned in the article. (company is it's own model).

I want a template that prints out a list of the articles, sorted by category, and also listing the companies mentioned.

However, I'm hitting two issues.

Firstly, the company field is a ManyToMany field. I'm printing this successfully now, using the all iterable, thanks to this SO question =). (Curious though, where is this all iterable documented in the Django documentation?)

listing objects from ManyToManyField

However, I'd like to print ", " (comma followed by space) after each item, except the last item. So the output would 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 Django's templating system?

Secondly, each Article has a CharField, called category, that stores the category for the article. I would like the articles sorted by Categories, if possible. So I use QuerySet, and get a nice list of relevant articles in article_list. I then use the regroup template tag to sort this into categories and print each one.

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

However, I need to make sure that my input list is sorted, before I pass it to regroup. 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?

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

Cheers, Victor

like image 289
victorhooi Avatar asked Jul 05 '10 06:07

victorhooi


2 Answers

Try forloop.last for your first question

{% for company in article.companys.all %}
  {{company.name}}{% if not forloop.last %}, {% endif %}
{% endfor %}
like image 195
czarchaic Avatar answered Oct 30 '22 14:10

czarchaic


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.

like image 20
maersu Avatar answered Oct 30 '22 13:10

maersu