来自 Django ORM 的联合查询

Union query from Django ORM

需要从 2 个不同的表中提取聚合数据。

Elements 
element_type   tempcolumn
   xyz            test1
   pqr            test2
   xyz            test3

Users: 
  User_names           
   auser
   buser
   cuser

需要按以下格式输出

element_type    count
  xyz             2 
  pqr             1 
  users           3

SQL 查询示例:

SELECT element_type, count(*) 
  FROM Elements group by element_type

union

  select 'users',count(*) from Users

我们可以用 django orm 执行同样的操作吗?

在 Django 上,您可以使用 | 来连接两个查询集,但我在这里不使用它。

因为 values/annotate 实际上是 returns 元组列表而不是 query_set

你可以在 Django 上 运行 raw SQL 但 raw 是为了优化。 https://docs.djangoproject.com/en/1.9/topics/db/sql/

object_count = Elements.objects.all().values('element_type').annotate(total=Count('element_type'))
response_data = {}
for q in object_count:
    if q['element_type'] == 'xyz':
        response_data['total_ xyz'] = q['total']
    if q['element_type'] == 'pqr':
        response_data['total_ pqr'] = q['total']
response_data['users_count'] = MyUser.objects.all().count()