【发布时间】:2017-02-24 20:39:46
【问题描述】:
我在 Django 中有以下模型:
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
country = models.ForeignKey(Country)
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ForeignKey(Author)
pubdate = models.DateField()
如何获得按作者首次出版图书时间排序的查询集?
在 SQL 中,我可以这样做:
SELECT *
FROM ( SELECT author_id
, MIN(pubdate) as date
FROM books
GROUP
BY author_id
HAVING
MIN(pubdate)) AS first_published
JOIN author
ON author.id = first_published.author_id
LIMIT 15
OFFSET 15
ORDER
BY first_published.author_id
使用 Django 已经有一段时间了,我还没有弄清楚如何做到这一点。
现在这很糟糕:
from django.db.models.sql.compiler import SQLCompiler
_quote_name_unless_alias = SQLCompiler.quote_name_unless_alias
SQLCompiler.quote_name_unless_alias = lambda self,name: name if name.startswith('(') else _quote_name_unless_alias(self,name)
subquery = "(SELECT author_id, MIN(pubdate) as first_release_date FROM app_books GROUP BY author_id HAVING MIN(pubdate)) AS releases"
condition = "releases.author_id = app_authors.id"
order = '-releases.first_release_date'
Author.objects.get_queryset().extra(tables=[subquery], where=[condition]).order_by(order)
【问题讨论】:
标签: python sql django django-models django-orm