【问题标题】:How can I select and order items based on a subquery?如何根据子查询选择和订购商品?
【发布时间】: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


    【解决方案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')
    

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 2017-01-29
      • 1970-01-01
      • 2012-06-08
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2019-11-25
      相关资源
      最近更新 更多