0
我有3个表格:Continent
,Country
和Story
。从相关表中提取数据
Country
有ForeignKey(Continent)
和Story
有ManyToManyField(Country, blank=True)
字段。
我需要的是获得至少有一个故事属于它的国家列表,我需要这些国家按大洲分组。
我该如何做到这一点?
我有3个表格:Continent
,Country
和Story
。从相关表中提取数据
Country
有ForeignKey(Continent)
和Story
有ManyToManyField(Country, blank=True)
字段。
我需要的是获得至少有一个故事属于它的国家列表,我需要这些国家按大洲分组。
我该如何做到这一点?
一种方式来做到这一点是:
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)
,将做的工作。
再见
谢谢你的工作,但它创造了太多的查询(271查询)! – 2013-05-10 22:12:07