python - Fetching data from related tables -


i have 3 tables: continent, country , story.

country has foreignkey(continent) , story has manytomanyfield(country, blank=true) field.

what need list of countries @ least have 1 story belonging it, , need these countries grouped continents.

how can achieve that?

one way is:

countries = {}  country_list = country.objects.all()  c in country_list:     # check stories has country     stories = story.objects.filter(country_set__name__exact=c.name)      # if country have stories     if stories.count() > 0:         ## check initialize list         if not countries.has_key(c.continent.name):             countries[c.continent.name] = []          ## add country         countries[c.continent.name].append(c) 

that work.

bye


Comments

Popular posts from this blog

matlab - How to equate a structure array to structure array -

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -