Sql 如何使用django从每位作者那里获得最新的3本书
使用以下django模型:Sql 如何使用django从每位作者那里获得最新的3本书,sql,django,django-queryset,Sql,Django,Django Queryset,使用以下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.Dat
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...
或者,如果顺序应该始终相同,正如您定义的Meta一样
books = a.book_set.all()[:5]
如果你能做到这一点,我建议:
for a in Author.objects.all():
books = a.book_set.all().order_by('-pub_date')[:5]
print books #and/or process the entries...
或者,如果顺序应该始终相同,正如您定义的Meta一样
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
如果您担心查询速度,请在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
这会让你有更多的疑问。使用SQL会好得多,这会让您得到n个查询。使用SQL会更好。我使用的是mysql,这个版本的mysql还不支持“LIMIT&IN/ALL/ANY/somesubquery”,我不用担心用SQL编写查询。对于一个大表,您将看到仅仅构建索引的最大好处。我使用mysql,而这个版本的mysql还不支持“LIMIT&IN/ALL/ANY/somesubquery”,我不担心用SQL编写查询。对于一个大表,您将看到仅仅构建索引的最大好处。