How to query as GROUP BY in django?

前端 未结 9 1257
别跟我提以往
别跟我提以往 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:54

    You can also use the regroup template tag to group by attributes. From the docs:

    cities = [
        {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
        {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
        {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
        {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
        {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
    ]
    
    ...
    
    {% regroup cities by country as country_list %}
    
    
      {% for country in country_list %}
    • {{ country.grouper }}
        {% for city in country.list %}
      • {{ city.name }}: {{ city.population }}
      • {% endfor %}
    • {% endfor %}

    Looks like this:

    • India
      • Mumbai: 19,000,000
      • Calcutta: 15,000,000
    • USA
      • New York: 20,000,000
      • Chicago: 7,000,000
    • Japan
      • Tokyo: 33,000,000

    It also works on QuerySets I believe.

    source: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#regroup

    edit: note the regroup tag does not work as you would expect it to if your list of dictionaries is not key-sorted. It works iteratively. So sort your list (or query set) by the key of the grouper before passing it to the regroup tag.

提交回复
热议问题