I have this model (irrelevant fields hidden):
class Blog(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
is_published = models.BooleanField(default=False)
published_date = models.DateTimeField(null=True, default=None, blank=True)
I only want to get the latest post of each author, sorted by published date.
I have tried the following in my view:
blog_list = Blog.objects.filter(
is_published=True
).order_by('author', '-published_date').distinct('author')
Which works except this sorts all of the blog post in order of the author, not by published date.
The following would actually do the trick by switching the order by, but this throws an error in django:
blog_list = Blog.objects.filter(
is_published=True
).order_by('-published_date', 'author').distinct('author')
I've checked all of the similar questions to this one and haven't encountered a solution that works. I think this request should be pretty simple but I don't see any way of achieving this.
I was able to get this to work using the following:
blog_ids = Blog.objects.filter(is_published = True)\
.order_by('author_id', '-published_date')\
.distinct('author_id')\
.values('id', flat=True)
blog_list = Blog.objects.filter(id__in=blog_ids)\
.order_by('-published_date')
Which gets exactly what I wanted!!!!
More detail on this method can be found here: https://stackoverflow.com/a/32760239/2990550