简体   繁体   中英

How to get the latest 3 books from each author using django

Using the following django models:

class Author(models.Model):
   name = models.CharField(max_length=100)
   age = models.IntegerField()

class Book(models.Model):
    name = models.CharField(max_length=300)
    author = models.ForeignKey(Author)
    pubdate = models.DateField()
    class Meta:
        ordering = ('-pubdate')

How can i get the five latest books published by each author ?

I had considered iterate each author and get books published by the author slicing to 5.

for a in Author.objects.all():
    books = Book.objects.filter(author = a )[:5]
    print books #and/or process the entries... 

But, if the tables has a lot of records (maybe thousands of books), this could be slow and inefficient.

So, is there any other way to accomplish this with django (or a sql query) ?

I would suggest :

for a in Author.objects.all():
    books = a.book_set.all().order_by('-pub_date')[:5]
    print books #and/or process the entries... 

or, if the order should always be the same, as you define Meta,

    books = a.book_set.all()[:5]

should do the trick

If you're worried about the speed of the query, build an index on your pubdate field:

pubdate = models.DateField(db_index=True)

This should avoid scanning the entire table each time you run the query.

The SQL, in postgres, would be something like:

select b1.name, b1.author
from books b1
where b1.id in (
    select b2.id
    from books b2
    where b1.author = b2.author
    order by b2.pubdate desc
    limit 3)
order by b1.author, b1.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM