Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter on prefetch_related in Django

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

like image 547
alan Avatar asked Jun 06 '12 13:06

alan


2 Answers

As of Django 1.7, filtering prefetched objects is possible. See this SO answer, and the Django documentation.

like image 150
Webthusiast Avatar answered Nov 12 '22 20:11

Webthusiast


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
like image 25
jasisz Avatar answered Nov 12 '22 19:11

jasisz