本文介绍了django中嵌套的GROUP BY:返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经看到,但区别是:




  • 我需要得到一个对象的词典,而不是值(实际上不是 values()返回的事物的类型) )。

  • 我需要获得一个嵌套字典(即GROUP_BY上需要GROUP_BY)。



我的模型:

  class Cities .Model):
country = models.TextField()
region_or_state = models.TextField()
city = models.TextField()

我想通过国家/地区进行分类,其中,由 region_or_state 其中里面有城市列表



我想要得到

  {'美国':
{'加州':['旧金山','洛杉矶',...],
'德克萨斯州':['达拉斯'''休斯顿',...},
'德国':
{'巴伐利亚':['慕尼黑','纽伦堡',...}
}

但是,如前所述,列表中的城市应该是对象



我没有找到如何在Django中获取它,所以在python中使用 itertools 已经成功的外部GROUP_BY:
(帮助我这样做:):

  from itertools import groupby 

def show_cities(request):
queryset = CitiesTable.objects.all()
grouping_cities = []
unique_countries = []
for k,g in groupby(queryset,lambda x:x.country )
grouping_cities.append(list(g))
unique_countries.append(k)
return render(request,'cities / show_cities.html',
{'cities' :grouping_cities,'countries':unique_countries})

但是我没有设法组合所有的城市

解决方案

我恐怕我不会在...之间的对象, region_or_state 知道如何用django的查询来解决这个问题。可能没有解决方案,或者有可能涉及使用未记录的功能。



然而,在大多数情况下,python解决方案会做得很好。 Django可能不得不自己做类似的事情。



看起来你的当前代码可能会有一个小问题。在使用 itertools.groupby 之前,您应该几乎总是排序条目,这是一个常见的陷阱,所以我很惊讶它不会自动排序。 Groupby遍历迭代,并在每次键值更改时创建一个新组。所以要完全组合一个迭代,你需要先按键排序。



这里你可以使用数据库进行排序,只需使用 groupby 两次:

  queryset = CitiesTable.objects.order_by('country','region_or_state') 

countries_dict = {}

为groupby的群组(queryset,lambda x:x.country):
countries_dict [country] = {}
for region,groupby中的inner_group(group,lambda x:x.region_or_state):
countries_dict [country] [region] = list(inner_group)


I'm trying to use a classic database GROUP_BY on my queryset in Django.

I've already seen How to query as GROUP BY in django? but the distinction is :

  • that I need to get a dictionnary of objects, not values (indeed not the type of thing returned by values()).
  • that I need to get a nested dictionary (i.e, I need to GROUP_BY on GROUP_BY).

My model:

class CitiesTable(models.Model):
    country = models.TextField()
    region_or_state = models.TextField()
    city = models.TextField()

I want to classify by country, then, among them, by region_or_state where inside there's the list of the city:

I want to get

{'USA':
    {'California': ['San Francisco', 'Los Angeles', ...],
     'Texas': ['Dallas', 'Houston', ...},
 'Germany':
     {'Bavaria': ['Munich', 'Nuremberg', ...}
}

But here, as noted previously, the cities inside the list should be Objects.

I didn't find how to get it in Django so, using itertools in python, I've already succeeded for the outer GROUP_BY:(helping me with this : How to convert tuple to a multi nested dictionary in python?):

from itertools import groupby

def show_cities(request):
    queryset = CitiesTable.objects.all()
    grouped_cities = []
    unique_countries = []
    for k, g in groupby(queryset, lambda x: x.country):
        grouped_cities.append(list(g))
        unique_countries.append(k)
    return render(request, 'cities/show_cities.html',
                  {'cities':grouped_cities, 'countries':unique_countries})

But I didn't manage to group all the cities objects in their region_or_state.

解决方案

I'm afraid I don't know how to solve this problem with django's querysets. There may not be a solution, or if there is it probably involves using undocumented features.

However, the python solution would do fine in most cases. Django would probably have to do something similar itself anyway.

It looks like there may be a slight issue with your current code. You should almost always sort your entries before using itertools.groupby - it's a common trap, so much so that I'm surprised it doesn't sort automatically. Groupby iterates through the iterable, and creates a new group every time the value of the key changes. So to fully group an iterable, you need to sort first by the key.

Here you could do the sorting using the database, and simply use groupby twice:

queryset = CitiesTable.objects.order_by('country', 'region_or_state')

countries_dict = {}

for country, group in groupby(queryset, lambda x: x.country):
    countries_dict[country] = {}
    for region, inner_group in groupby(group, lambda x: x.region_or_state):
        countries_dict[country][region] = list(inner_group)

这篇关于django中嵌套的GROUP BY:返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:30
查看更多