Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Ordering objects by their children's attributes

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:

  • The author on top is the one who most recently published a book
  • The next one is the one who published books not as new as the first,
  • So on etc.

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?

like image 648
cwj Avatar asked Oct 30 '25 13:10

cwj


1 Answers

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.

like image 195
Ofri Raviv Avatar answered Nov 01 '25 05:11

Ofri Raviv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!