简体   繁体   中英

django populating queryset into a dictionary

am not quite advanced python user, I am stuck trying to populate the below but I think am handling list_choices wrong.

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

Below the error am getting

>>> 
>>> 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'

That is because you use setdefault without a second argument. And it returns None in this case.

Try this fixed code:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM