按两列分组,按一个列分开,按计数

时间:2016-12-13 21:46:28

标签: python django

在问题的标题上苦苦挣扎:)

我是python& amp;的初学者django,我有一个问题,我正在尝试制作

我的(简化)模型是:用户,旅行,国家。

用户可以在他想要的任何国家创建他想要的许多旅行。 他也可以创建多次到同一个国家的旅行。

我的目标是获取不同用户+计数创建的旅程最多的前15个国家/地区。意味着如果一个用户创建了10次到同一个国家/地区的旅行,则认为它是一个。

到目前为止我所取得的成就是

    hottest_countries = models.Event.objects.values('country')\
                      .exclude(creator=None) \
                      .annotate(count=Count('country'))\
                      .distinct() \
                      .order_by('-count')[:15]

这将返回每个国家的国家和统计数,但不会返回不同的用户

所以我已将代码更改为

    hottest_countries = models.Event.objects.values_list('country', flat=True)
                      .exclude(creator=None) \
                      .annotate(count=Count('country'))\
                      .distinct() \
                      .order_by('-count')[:15]

    # Getting all the creators of each country
    creators_for_country = [models.Event.objects.values_list('creator', flat=True).filter(Q(country=country_id)).distinct() for country_id in hottest_countries]

    # Sorting again to make sure
    hots_events_sorted = [{"country_id": country_id, "count": len(creators_for_country[idx]), "creators": creators_for_country[idx]} for idx, country_id in enumerate(hottest_countries)]
    hots_events_sorted.sort(key=itemgetter('count'), reverse=True)

它正在运作,但是:

一个。我认为这很复杂。并且必须更容易。

B中。可能是我在第一个查询中获取的前15个国家实际上并不是正确的,因为可能是第二个查询在创建者不同时减少了所有条目。对于前者一位用户创建了1000次加拿大之旅。这会将第一个查询中的国家/地区推到列表顶部。但是当我们通过创作者区分列表时,我们会得到一个条目。这使得加拿大名列榜首甚至根本没有。

注意:当我尝试使用给定列进行区分时,我遇到了数据库错误,我的数据库不支持列不相同..

1 个答案:

答案 0 :(得分:0)

如果有人像我一样挣扎,这是我的解决方案。

在注释中添加distinct=True解决我的问题

hottest_countries = models.Event.objects.values('country')\
                  .exclude(creator=None) \
                  .annotate(count=Count('creator', distinct=True))\
                  .distinct() \
                  .order_by('-count')[:15]
相关问题