5 Ways to Get the Latest Book Per Author in Django
In a Django application, fetching the latest record for each group is a common yet challenging task, especially when working with large datasets. Whether you’re building an analytics dashboard or managing grouped data, finding an efficient solution is key. In this blog post, we’ll explore five different approaches to tackle this problem, ranked from least to most effective based on performance and readability, using the following Book model: class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( Author, on_delete=models.CASCADE, related_name="books" ) genre = models.CharField(max_length=255) published_at = models.DateTimeField() is_featured = models.BooleanField(default=False) Solution 1: Python Max with Prefetch latest_books = [ max(author.books.all(), key=lambda x: x.published_at, default=None) for author in Author.objects.prefetch_related("books") ] Performs heavy computation in Python rather than leveraging the database, which is bad for performance. Also makes two database queries (better solutions do it in one). ...