Sorting objects in template

大城市里の小女人 提交于 2019-12-04 03:47:27

问题


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 view:

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'd like to sort words in template by number of votes and by pub date, separately. How can I do this?


回答1:


You can make custom template tag or filter, which gets words set and sorting type as parameters.

For example (haven't tested):

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 %}
...



回答2:


You can do it in the views

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



回答3:


You can also:

  1. add special method in Category model,
  2. add simple shortcut method in custom Related Manager for Word,
  3. make this ordering default one in Word (I don't like this one to be honest)


来源:https://stackoverflow.com/questions/12238939/sorting-objects-in-template

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