Yax
Yax

Reputation: 2189

Get Latest from Python Sorted() Not Working in Django

I am combining two Django Queryset and I want to be able to get the latest 10 out of the combo. I want to display them in descending order, of date, in my template - so that the latest Articles gets displayed first.

import itertools

articles = Articles.object.filter(conditions)[:10]
shared_articles = Shares.object.filter(conditions)[:10]

all_articles = sorted(itertools.chain(articles, shared_articles), 
                      key=lambda x: x.date_created, reverse=True)[-10:]

Now if I do the following in my template, the oldest articles get displayed first:

{% for article in all_articles %}
    <h3>{{article.header}}</h3>
    <p>{{article.content}}</p>
{% endfor %}

How do I get it to display the latest first?

Upvotes: 0

Views: 68

Answers (1)

falsetru
falsetru

Reputation: 369474

You can used reversed in for tag:

{% for article in all_articles reversed %}
    <h3>{{article.header}}</h3>
    <p>{{article.content}}</p>
{% endfor %}

Upvotes: 4

Related Questions