django:SQL UNION或与queryset连接:与annotate一起使用时无法正常工作

时间:2017-05-10 18:35:16

标签: django-models django-queryset django-aggregation

我有以下两个查询集books1和books2。在我同时使用annotate为books1添加另一个常量为10的列,为books2添加30。问题是在我连接查询集之后,最终集显示annotate值= 10,即使对于books2

author1 = Author.objects.get(pk=1)

books1 = author1.books_set.annotate(sample_var=Value(10))

author2 = Author.objects.get(pk=2)

books2 = author2.books_set.annotate(sample_var=Value(30))

combine = books1 | books2

我所看到的:

name                  author id       sample_var
name1 (from books1)       1                10
..                        1                10
..                        1                10
..                        1                10
name2 (from books2)       2                10 (instead of 30) 
..                        2                10 (instead of 30) 
..                        2                10 (instead of 30) 
..                        2                10 (instead of 30) 

原因是,用于联合收割机的sql如下。当我尝试访问combine [0] .name时,我得到了这个。它负责WHERE部分,但不处理注释部分。它使用10 AS“sample_var”作为组合查询集,这是不正确的,这就是为什么所有在上表中显示10。

SELECT "books_books"."name", "books_books"."author_id", 10 AS "sample_var"
FROM "books_books" 
WHERE ("books_books"."author_id" = 1 OR "books_books"."author_id" = 2)

我认为如果联盟恰当地发生了sql应该是:

SELECT "books_books"."name", "books_books"."author_id", 10 AS "sample_var"
FROM "books_books" 
WHERE ("books_books"."author_id" = 1)
union all
SELECT "books_books"."name", "books_books"."author_id", 30 AS "sample_var"
FROM "books_books" 
WHERE ("books_books"."author_id" = 2)

1 个答案:

答案 0 :(得分:0)

在Django 1.11中,您可以执行union,在您的情况下:

all_books = books1.union(books2, all=True)