ejasquith
ejasquith

Reputation: 65

How to get only the most recent post from each user, ordered by created date

I'm trying to create a social media site in Django where the homepage will display a list of each friend's most recent post, with the newest at the top. At the moment I'm ignoring the friendship functionality and just displaying posts from all users.

My current code gets the most recent post from users, but doesn't then order that list by created date.

views.py:

class PostList(generic.ListView):
    model = Post
    # Gets the most recent post from each user
    # However, the returned set is not ordered by created_on
    queryset = Post.objects.order_by('author', '-created_on').distinct('author')
    template_name = 'home.html'

I can't change the order_by call as it throws this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions

I know it's possible because I did it ~5 years ago but I don't know what approach I took then and the code is lost.

Upvotes: 1

Views: 88

Answers (1)

nigel239
nigel239

Reputation: 1765

If you could access the usermodel in the template, you could do this:

{% for friend in friends %}
    {% for post in friend.posts_set.all|dictsort:"created_at" %} // or dictsortreversed 
        {{post.data}}
    {%endfor%}
{%endfor%}

If you have custom user models, go the extra step and define some methods on that to access the posts:

class User(models.Model):
    ....
    def get_latest_posts(self):
        return self.posts_set.all().order_by("-created_on")

And then in the template access it like:

{% for friend in friends %}
    {% for post in friend.get_latest_posts %}
        {{post.data}}
    {% endfor %}
{% endfor %}

Upvotes: 1

Related Questions