Django将queryset填充到字典中

2024-04-20 16:11:53 发布

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

但我认为用户在处理下面的选项时并没有错。在

class LocationManager(TranslationManager):
    def get_location_list(self, lang_code, site=None):
        # this function is for building a list to be used in the posting process
        # TODO: tune the query to hit database only once
        list_choices = {}
        for parents in self.language(lang_code).filter(country__site=site, parent=None):    
            list_child = ((child.id, child.name) for child in self.language(lang_code).filter(parent=parents))
            list_choices.setdefault(parents).append(list_child)

        return list_choices

低于错误值

^{pr2}$

Tags: thetoinselfnonechildlangfor
1条回答
网友
1楼 · 发布于 2024-04-20 16:11:53

这是因为使用setdefault时没有第二个参数。在本例中,它返回None。在

请尝试以下固定代码:

# this is much more confinient and clearer
from collections import defaultdict

def get_location_list(self, lang_code, site=None):
    # this function is for building a list to be used in the posting process
    # TODO: tune the query to hit database only once
    list_choices = defaultdict(list)
    for parent in self.language(lang_code).filter(country__site=site, parent=None):
        list_child = self.language(lang_code).filter(parent=parent).values_list('id', 'name')
        list_choices[parent].extend(list_child)

    return list_choices

相关问题 更多 >