Consider the models:
class Author(models.Model):
name = models.CharField(max_length=200, unique=True)
class Book(models.Model):
pub_date = models.DateTimeField()
author = models.ForeignKey(Author)
Now suppose I want to order all the books by, say, their pub_date. I would use order_by('pub_date'). But what if I want a list of all authors ordered according to who most recently published books?
It's really very simple when you think about it. It's essentially:
I could probably hack something together, but since this could grow big, I need to know that I'm doing it right.
Help appreciated!
Edit: Lastly, would the option of just adding a new field to each one to show the date of the last book and just updating that the whole time be better?
from django.db.models import Max
Author.objects.annotate(max_pub_date=Max('books__pub_date')).order_by('-max_pub_date')
this requires that you use django 1.1
and i assumed you will add a 'related_name' to your author field in Book model, so it will be called by Author.books instead of Author.book_set. its much more readable.
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