简体   繁体   English

如何使用django从每位作者那里获得最新的三本书

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

Using the following django models: 使用以下django模型:

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. 我考虑过迭代每个作者,并得到该作者出版的书籍,分为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) ? 那么,还有其他方法可以通过django(或sql查询)完成此操作吗?

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字段上建立索引:

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: 在postgres中,SQL类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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