[Answer]-Fetching data from related tables

1👍

One way to do it is:

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)

That will do the work.

Bye

👤azuax

Leave a comment