我如何 select 并根据子查询订购商品?

How can I select and order items based on a subquery?

我在 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)

试试这个

Author.objects.all().annotate(s=Min('book__pubdate')).order_by('s')

当某些作者没有书时

Author.objects.exclude(book__pubdate__isnull=True).annotate(s=Min('book__pubdate')).order_by('s')