如何根据子查询选择和订购项目?

时间:2016-10-15 13:36:56

标签: python sql django django-models django-orm

我在Django中有以下模型:

var taschenQuelle = Folder.selectDialog();
alert("Click OK to start processing.", "TEASER 2014");
var listeAllerTaschen = taschenQuelle.getFiles();

如何在第一次出版图书时获取作者的查询集?

在SQL中,我可以使用以下方法执行此操作:

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()

Django已经有一段时间了,我还没弄清楚如何做到这一点。

现在这只是讨厌:

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

1 个答案:

答案 0 :(得分:1)

试试这个

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')