[英]How to get the latest 3 books from each author using django
使用以下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')
我如何获得每位作者出版的五本最新书籍 ?
我考虑过迭代每个作者,并得到该作者出版的书籍,分为5部分。
for a in Author.objects.all():
books = Book.objects.filter(author = a )[:5]
print books #and/or process the entries...
但是,如果表中有很多记录(也许是数千本书),则可能会很慢且效率低下。
那么,还有其他方法可以通过django(或sql查询)完成此操作吗?
我会建议 :
for a in Author.objects.all():
books = a.book_set.all().order_by('-pub_date')[:5]
print books #and/or process the entries...
或者,如果顺序应始终相同,则在您定义元时,
books = a.book_set.all()[:5]
应该可以
如果您担心查询的速度,请在pubdate字段上建立索引:
pubdate = models.DateField(db_index=True)
这应该避免每次运行查询时都扫描整个表。
在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.