Django complex query to fetch data from groupby an

2019-07-21 21:19发布

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条回答
虎瘦雄心在
2楼-- · 2019-07-21 22:14

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.

查看更多
登录 后发表回答