【问题标题】:django: SQL UNION or concatenate with queryset: not working properly when used with annotatedjango:SQL UNION 或与查询集连接:与注释一起使用时无法正常工作
【发布时间】:2017-10-09 13:31:32
【问题描述】:

我有以下两个查询集books1 和books2。在两者上,我都使用 annotate 添加另一列,book1 的常数为 10,books2 的常数为 30。问题是在我连接查询集之后,最终集显示注释值 = 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)

【问题讨论】:

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


    【解决方案1】:

    在 Django 1.11 中,您可以使用 union,在您的情况下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2019-09-25
      • 2014-02-01
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多