Python django将queryset填充到字典中

Python django将queryset填充到字典中,python,django,django-nani,Python,Django,Django Nani,我不是一个非常高级的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

我不是一个非常高级的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
下面是我得到的错误

>>> 
>>> Location.objects.get_location_list(lang_code='en', site=current_site)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/mo/Projects/mazban/mazban/apps/listing/geo/models.py", line 108, in get_location_list
    list_choices.setdefault(parents).append(list_child)
AttributeError: 'NoneType' object has no attribute 'append'
>
>>>Location.objects.get\u Location\u列表(lang\u code='en',site=current\u site)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/home/mo/Projects/mazban/mazban/apps/listing/geo/models.py”,第108行,在获取位置列表中
list_choices.setdefault(父项).append(list_子项)
AttributeError:“非类型”对象没有属性“附加”

这是因为您使用的
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

请提供您的型号代码。列表\u选项总是返回空。错误中的行不会显示在上面的代码中。@Thomas,对不起,我的错误。我刚刚更新了代码above@MoJ:你能解释一下你想要什么样的输出吗?代码显然是错的,但我不知道你想要什么。