Is there a way of filtering prefetched objects? I need to get the latest() of the prefetched objects but prefetch_related doesn't work if you use latest because the query is changed?
The example here does what I need but I was hoping there's a simpler workaround...
https://github.com/ionelmc/django-prefetch#example
As of Django 1.7, filtering prefetched objects is possible. See this SO answer, and the Django documentation.
It is very simple method which is hardly comparable with those app, but hope you will find it useful:
class Author(models.Model):
name = models.CharField(max_length=100)
def latest_book(self):
return max(self.book_set.all(), key=lambda book: book.created)
authors = Author.objects.prefetch_related('book_set')
authors[0].latest_book() # what you wanted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With