Step 1:
Suppose I have two one->many related models such as:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
name = models.CharField(max_length=300)
author = models.ForeignKey(Author)
pubdate = models.DateField()
How can I get a list of all authors and the name of their last book (or rather the book object itself)?
- Without one query per article
- Some authors may not have published a book yet, I still want them in the list (with None)
- For portability I want to avoid manual SQL
- It should not load all Books in memory
Step 2:
I am not sure that is a significant difference in the solution.
Suppose now I have I PictureBook subclass of the Book (using django-polymorphic) and I want to know the the picture_url of all authors last PictureBook (and again None if not).
from polymorphic import PolymorphicModel
class Book(PolymorphicModel):
name = models.CharField(max_length=300)
author = models.ForeignKey(Author)
pubdate = models.DateField()
class PictureBook(Book):
picture_url = models.CharField(max_length=200)
Unfortunately the examples in the documentation about annotate only show direct Min/Max values. If I would start with all PictureBooks, then I would miss the authors that don't have one. This question is somwhat related, but very old. I am using Django 1.7.