如何使用 django 获取每个作者最新的 3 本书
使用以下 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 查询)来完成此任务?
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) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议:
或者,如果顺序应该始终相同,正如您定义的 Meta 那样,
应该可以解决问题
I would suggest :
or, if the order should always be the same, as you define Meta,
should do the trick
如果您担心查询的速度,请在 pubdate 字段上构建索引:
这应该避免每次运行查询时扫描整个表。
postgres 中的 SQL 类似于:
If you're worried about the speed of the query, build an index on your pubdate field:
This should avoid scanning the entire table each time you run the query.
The SQL, in postgres, would be something like:
对我来说,我有
3 位作者
,每个作者都至少有300 篇帖子
。我测试了两种方法,差异非常引人注目!
根据
django-debug-toolbar
显示,第一种方法有3个类似的查询
,其中3
是这里的作者数量,它需要总共8 个查询(+180 毫秒)
和CPU(400 - 800 毫秒)
,但第二个总共需要5 个查询(+80 毫秒) )
和CPU (+70 - 90 ms)
。SELECT ... FROMauthor
,我无法弄清楚为什么它被生成它似乎根本没有被使用。最简单和最熟悉的方法
更复杂和不熟悉的方法
如果您只需要帖子而不是作者:
以下获取数据的方式会少做一次查询,并且只返回帖子。
For me, I had
3 authors
and each of which had more than at least300 posts
.I tested two approaches and the difference is eye catching!
according to what
django-debug-toolbar
showed, first approach it had3 similar queries
which the3
is the number of authors here and it takes a total of8 queries (+180 ms)
andCPU (400 - 800 ms)
, but the second one takes a total of5 queries (+80 ms)
andCPU (+70 - 90 ms)
.SELECT ... FROM author
which I couldn't figure it out why it had been produced it seems not to be used at all.The simplest and most familiar approach
The more complicated and unfamiliar approach
If you just need the Posts and not the Authors:
the following way of fetching data does one less query and only returns the posts.