按两个列分组,按一个列不同,按国家排序

2024-04-18 16:50:54 发布

您现在位置:Python中文网/ 问答频道 /正文

与问题的标题很不相称:)

我是python&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次到加拿大的旅行。这会将第一个查询中的国家推到列表的顶部。但是当我们按创建者区分列表时,我们得到一个条目。这使得加拿大在名单上排名靠后,甚至根本没有。你知道吗

注意:当我尝试使用给定列进行distinct时,我得到了DB错误,即我的DB不支持distinct by columns。。你知道吗


Tags: 用户eventidforobjectsmodelscount国家
1条回答
网友
1楼 · 发布于 2024-04-18 16:50:54

如果有人像我一样挣扎,我的解决办法是。你知道吗

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

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

相关问题 更多 >