从相关表中获取数据

时间:2013-05-09 22:08:29

标签: python django

我有3个表:ContinentCountryStory

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

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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)

那将完成工作。

再见

相关问题