Sorting objects in a template

Let these models:

class Category(models.Model): name = models.CharField(max_length=20) class Word(models.Model): name = models.CharField(max_length=200) votes = models.IntegerField(default=1) categories = models.ManyToManyField(Category, null=True, blank=True) 

this kind:

 def main_page(request): words = Word.objects.all() categories = Category.objects.all() return render(request, "main_page.html", {'words': words}) 

and this template:

 {% for category in categories %} {% for word in category.word_set.all %} <p>{{ word }}</p> {% endfor %} {% endfor %} 

I would like to sort the words in the template by the number of votes and by date of publication, separately. How can i do this?

+4
source share
3 answers

You can make your own template tag or filter , which receives a set of words and a sort type as parameters.

For example (did not check):

custom_tags.py:

 from django import template register = template.Library() @register.filter def sort_by(queryset, order): return queryset.order_by(order) 

template.html

 {% load custom_tags %} ... {% for word in category.word_set.all|sort_by:'-votes' %} <p>{{ word }}</p> {% endfor %} ... 
+12
source

You can do it in views

 words = Word.objects.all().order_by('votes', 'pub_date') 
+4
source

You also can:

  • add a special method to the category model,
  • add a simple shortcut method to the custom Linked Manager for Word,
  • make this default order one in Word (I don't like that it's fair)
0
source

All Articles