1

There are similar questions here but I haven't been able to find one that helps me.

I have two models, Chat and Post

there are multiple Chats, and each chat has multiple posts attached to it. I'm trying to get the latest post for each chat.

Post.objects.order_by('-id').distinct('Chat')

Filter the posts by ID (so the newest post is first), and then grab the distinct ones based on the Chats.

but since order_by and distinct don't match I'm getting the error:

SELECT DISTINCT ON expressions must match initial ORDER BY expressions

So how exactly do I go about doing this? Rawsql? Thanks!

McFads
  • 81
  • 7

1 Answers1

0

If you use distinct by related model, you must use ordering based of this model:
Post.objects.order_by('chat', '-id').distinct('chat')
Also you can look at this question

Community
  • 1
  • 1
Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75