I have the following (simplified) models:
class Post(models.Model):
title=models.CharField(max_length=500)
class Recommendation(models.Model):
post=models.ForeignKey(Post)
submit_time=models.DateTimeField(auto_now_add=True)
And I want to get the list of distinct Posts ordered by Recommendation's submit time.
The first way I tried was the straighforward:
Post.objects.order_by('recommendation__submit_time').distinct()
But surprisingly this gave a QuerySet with duplicate Post objects. Turns out the rows are actually different because Django adds extra columns for the ordering, but does not return them in the results.
Looking around I found a couple answers on SO, including to use aggregation instead of ordering:
Post.objects.all().annotate(Max('recommendation__submit_time')).order_by('recommendation__submit_time__max')
Or to de-normalize the model and add a last_recommended_time field to Post.
Most of the questions/answers already in SO are a couple years old, so I was wondering if there’s a more idiomatic and straightforward way to do this than those suggested hacks.
EDIT:
Just thought I made it clear:
The solutions listed above do work and I’m using them (albeit not in production). I’m just interested in better solutions to this issue.
Have you thought about using raw sql