这里是一个抽象的简化示例。
说我想找作者并注释类别中最少的书籍(如果该数目大于3)。
书本和作者模型并且与ForeignKey字段无关(请记住,抽象和简化,这是有原因的):
Author(models.Model):
name = models.CharField(max_length=250)
Book(models.Model):
author_name = models.CharField(max_length=250)
book_category = models.CharField(max_length=250)
这是我可以重现的最简单的查询:
(Author.objects
.annotate(min_valuable_count=Subquery(
Book.objects
.filter(author_name=OuterRef('name'))
.annotate(cnt=Count('book_category'))
.filter(cnt__gt=3)
.order_by('cnt')
.values('cnt')[:1],
output_field=models.IntegerField()
))
)
我得到一个错误:
psycopg2.ProgrammingError: missing FROM-clause entry for table "U0"
LINE 1: ... "core_author" GROUP BY "core_author"."id", "U0"."id" ...
^
这是SQL:
SELECT "core_author"."id", "core_author"."name", (
SELECT COUNT(U0."book_category") AS "cnt"
FROM "core_book" U0 WHERE U0."id" = ("core_author"."chat_id")
GROUP BY U0."id" HAVING COUNT(U0."book_category") > 3
ORDER BY "cnt" ASC LIMIT 1)
AS "min_valuable_count"
FROM "core_author"
GROUP BY "core_author"."id", "U0"."id"
更新#1
我发现删除.filter(cnt__gt=3)
会删除无法访问GROUP BY
的最后U0
:
SELECT "core_author"."id", "core_author"."name", (
SELECT COUNT(U0."book_category") AS "cnt"
FROM "core_book" U0 WHERE U0."id" = ("core_author"."chat_id")
GROUP BY U0."id"
ORDER BY "cnt" ASC LIMIT 1)
AS "min_valuable_count"
FROM "core_author"
是否可以在不删除子查询中的GROUP BY
的情况下在外部查询中删除.filter(cnt__gt=3)
?
答案 0 :(得分:0)
这是bug,将在Django 2.1.6版中修复。现在是工作区:
min_valuable_count_qs = Subquery(
Book.objects
.filter(author_name=OuterRef('name'))
.annotate(cnt=Count('book_category'))
.filter(cnt__gt=3)
.order_by('cnt')
.values('cnt')[:1],
output_field=models.IntegerField()
)
min_valuable_count_qs.contains_aggregate = False
qs = Author.objects.annotate(min_valuable_count=min_valuable_count_qs))