django: sort by foreignkey in model manager
Question: 
    class Author(models.Model):
        name = models.CharField()
    
    class Article(models.Model):
        author = models.ForeignKey(Author)
        created_at = models.DateTimeField(auto_now_add=True)
    

In a custom model manager for `Author`, how could one proceed to sort all the
authors by the creation date of their most recent `Article`? Is this possible
without using raw sql or for loops?

To show research effort and clarify the question, here's the (pseudo)code of
how I'd do that in raw Python. It is untested and would probably not work
because of the `if not article.author in sorted_authors` condition.

    
    
    from django.db import models
    from .models import Article
    
    class AuthorsManager(models.Manager):
        def get_sorted_authors(self):
    
            articles = Article.objects.all().order_by('creation_date')
    
            sorted_authors = []
            for article in articles:
                # not sure if this if condition would work
                if not article.author in sorted_authors:
                    sorted_authors.append(article.author)
    
            return sorted_authors
    

* * *

Another possible solution: add a `last_article_datetime` field to `Author` and
sort by that. Widely more efficient and concise. Question still standing for
any other use-case though.


Answer: Maybe like this:

    
    
    Author.objects.annotate(lc=Max('article__created_at')).order_by('lc')
    

