Django complex query to fetch data from groupby and having clause

穿精又带淫゛_ 提交于 2019-12-12 18:23:38

问题


I want to execute group by clause on MyUser table having CNT.Status exactly one the raw query would be like below.

SELECT user_id from user_table GROUP BY user_id HAVING COUNT(status)=1

I tried various options using Django model API but its adding "id" too in group by clause.


回答1:


It seems you are looking for filtering on annotations:

qs = ( MyUser
      .objects
      .annotate(num_status=Count('status'))
      .filter(num_status__gt=1)
     )

Notice: I supose that status is a 1:N related model.



来源:https://stackoverflow.com/questions/14827899/django-complex-query-to-fetch-data-from-groupby-and-having-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!