How to query as GROUP BY in django?

前端 未结 9 1255
别跟我提以往
别跟我提以往 2020-11-22 05:40

I query a model:

Members.objects.all()

And it returns:

Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2         


        
9条回答
  •  感情败类
    2020-11-22 05:57

    An easy solution, but not the proper way is to use raw SQL:

    results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation')
    

    Another solution is to use the group_by property:

    query = Members.objects.all().query
    query.group_by = ['designation']
    results = QuerySet(query=query, model=Members)
    

    You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.

    And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.

提交回复
热议问题