【问题标题】:Django: output aggregation of aggregation ordered by countsDjango:按计数排序的聚合的输出聚合
【发布时间】:2010-08-25 00:29:17
【问题描述】:

我正在尝试在我的 django 模板中输出以下数据。

国家/地区将按故事数降序排列。 城市将按故事数降序排列(在该国家/地区下)

Country A(# of stories)
  City A (# of stories)
  City B (# of stories)

Country B(# of stories)
  City A (# of stories)
  City B (# of stories)

我的模型如下:

# Create your models here.
class Country(models.Model):
    name = models.CharField(max_length=50)

class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey(Country)

class Story(models.Model):
    city = models.ForeignKey(City)
    country = models.ForeignKey(Country)
    name = models.CharField(max_length=255)

最简单的方法是什么?

【问题讨论】:

标签: python django aggregate


【解决方案1】:

这个解决方案对我有用。不过,您需要对其进行调整以将其传递给模板。

from django.db.models import Count
all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')

for country in all_countries:
    print "Country %s (%s)" % (country.name, country.story__count)
    all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
    for city in all_cities:
        print "\tCity %s (%s)" % (city.name, city.story__count)

更新

这是将此信息发送到模板的一种方式。这涉及到使用自定义过滤器。

@register.filter
def get_cities_and_counts(country):
    all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
    return all_cities

查看:

def story_counts(request, *args, **kwargs):
    all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
    context = dict(all_countries = all_countries)
    return render_to_response(..., context)

在你的模板中:

{% for country in all_countries %}
    <h3>{{ country.name }} ({{ country.story__count }})</h3>
    {% for city in country|get_cities_and_counts %}
        <p>{{ city.name }} ({{ city.story__count }})</p>
    {% endfor %}
{% endfor %}

更新 2

模型中带有自定义方法的变体。

class Country(models.Model):
    name = models.CharField(max_length=50)

    def _get_cities_and_story_counts(self):
        retrun City.objects.filter(country = self).annotate(Count('story')).order_by('-story__count')
    city_story_counts = property(_get_cities_and_story_counts)

这可以让您避免定义过滤器。模板代码更改为:

{% for country in all_countries %}
    <h3>{{ country.name }} ({{ country.story__count }})</h3>
    {% for city in country.city_story_counts %}
        <p>{{ city.name }} ({{ city.story__count }})</p>
    {% endfor %}
{% endfor %}

【讨论】:

  • 谢谢,但是有没有一种自然的方法可以将它传递到我可以在模板中工作的数据结构中?还是我现在需要构建一个自定义字典?
  • 添加了一种方法。这涉及到一个过滤器。
  • 我喜欢这个答案,但想知道是否有更“django”的方式来做这件事。类似这个答案,stackoverflow.com/questions/1010848/…
  • @Maverick:我明白你的意思。但是(没有向模型添加方法)我找不到直接获取每个国家/地区模板中每个城市的计数的方法:(
  • @Maverick:更新了答案。见上文。
猜你喜欢
  • 2017-12-31
  • 2019-08-05
  • 2019-03-09
  • 2021-12-13
  • 2015-02-10
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多