来自Django ORM的联盟查询

时间:2017-05-12 12:27:28

标签: python django 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执行相同的操作吗?

1 个答案:

答案 0 :(得分:1)

在Django上,您可以使用|加入两个查询集,但我不是在这里使用它。

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

你可以在Django上运行原始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()