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?

Edit
Report