[Answer]-Getting related models from queryset of one-to-many relation with polymorphism

1👍

In your first example, if the relationship were set up like:

from django.db import models
class Author(models.Model):
    name = models.CharField(max_length=100)
    books = models.ManyToMany(Book)

    def latest_book(self):
        """ 
        This is only efficient / accurate if you've prefetched books 
        in the right order!
        """
        if self.books.exists():
            return self.books.all()[0]
        return None


class Book(models.Model):
    name = models.CharField(max_length=300)
    pubdate = models.DateField()

Then with the Prefetch object introduced in 1.7:

from django.db.models import Prefetch
authors = Author.objects.all().prefetch_related(
    Prefetch('books', queryset=Books.objects.order_by('-pubdate')

for author in authors:
    print author.latest_book()

2 database queries, but of course be aware that you are loading every book for every author into memory. That said, using the Prefetch object’s queryset arg you could probably make this more efficient.

I made latest_book a member of Author to keep the sample code light, but in reality you’d probably want this outside the Author model’s definition, since its not useful outside this specific implementation with the proper prefetch called.

I’m not familiar with the django-polymorphic package, but I’m betting you can use this approach to your advantage, as prefetching supports generic relationships also.

Leave a comment