来自Django ORM的联合查询

2024-10-04 03:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

需要从2个difrent表获取聚合数据。在

Elements 
element_type   tempcolumn
   xyz            test1
   pqr            test2
   xyz            test3

Users: 
  User_names           
   auser
   buser
   cuser

需要以下格式的输出

^{pr2}$

SQL查询示例:

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

union

  select 'users',count(*) from Users

我们能和django orm一样吗?在


Tags: 数据namestypecountelementselementuserstest1
1条回答
网友
1楼 · 发布于 2024-10-04 03:26:28

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

因为values/annotate实际上返回元组列表而不是查询集

您可以在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()

相关问题 更多 >