Python Django按字段分组并获取与该特定字段相关的所有项目

Python Django按字段分组并获取与该特定字段相关的所有项目,python,django,Python,Django,我使用的是Django3.1.1,我有一个新闻模型,它有一个名为source_name的字段 课堂新闻(models.Model): title=models.CharField(最大长度=350) content=RichTextField(blank=True,null=True) link=models.URLField(最大长度=500,唯一性=True) #来源 source\u name=models.CharField(最大长度=100) 我想把每一条新闻按来源的名称分组,对于每

我使用的是Django3.1.1,我有一个新闻模型,它有一个名为source_name的字段

课堂新闻(models.Model):
title=models.CharField(最大长度=350)
content=RichTextField(blank=True,null=True)
link=models.URLField(最大长度=500,唯一性=True)
#来源
source\u name=models.CharField(最大长度=100)
我想把每一条新闻按来源的名称分组,对于每一个来源,我想得到所有的新闻

News(title='test',source_name='AAA',...)
News(title='test-1',source_name='AAA',...)
News(title='test-2',source_name='AAA',...)
News(title='test-B',source_name='BBB',...)
News(title='test-B1',source_name='BBB',...)
在html模板中,我希望获得以下输出

- AAA
  -test
  -test-1
  -test-2
- BBB
  -test-B
  -test-B1
如果我能完成以下循环,那就很容易了:

{% for source in source_names %}
    {{ source }}
    {% for news in source %}
        {{news.title}}
    {% endfor %}
{% endfor %}
如何在django模板中实现上述输出?
谢谢

请按照您的要求准备好数据:

source_values = ['a', 'b', 'c']
data = { s: News.objects.filter(source=s) for s in source_values }
然后在模板中

{% for source, news_list in data.items %}
    {{source}}
    {% for n in news_list %}
        {{n.title}}
    {% endfor %}
{% endfor %}

我根据这段代码设法解决了这个问题

grouped={}#dict
对于News.objects.all()中的obj:
grouped.setdefault(obj.type,[]).append(obj)
在我使用的模板中:

{% for source, news_list in grouped.items %}
    {{source}}
    {% for n in news_list %}
        {{n.title}}
    {% endfor %}
{% endfor %}