2013-05-09 96 views
0

我有3个表格:ContinentCountryStory从相关表中提取数据

CountryForeignKey(Continent)StoryManyToManyField(Country, blank=True)字段。

我需要的是获得至少有一个故事属于它的国家列表,我需要这些国家按大洲分组。

我该如何做到这一点?

回答

1

一种方式来做到这一点是:

countries = {} 

country_list = Country.objects.all() 

for c in country_list: 
    # check the stories that has the country 
    stories = Story.objects.filter(country_set__name__exact=c.name) 

    # only if the country have stories 
    if stories.count() > 0: 
     ## check for initialize list 
     if not countries.has_key(c.continent.name): 
      countries[c.continent.name] = [] 

     ## finally we add the country 
     countries[c.continent.name].append(c) 

,将做的工作。

再见

+0

谢谢你的工作,但它创造了太多的查询(271查询)! – 2013-05-10 22:12:07