I’m creating an app where people will be able to make posts for cities. I’d like to create a view for the country, which would show a list of cities that have posters, and a count of how many posters have been made for each city.
I have a Country table, and a City table with a foreign key for a country. I also have a Poster table with a foreign key to the City table.
This successfully gives me a list of posters, but how do I group them into Cities and pass that? In the template I’d like to be able to show the City Name, poster.image that are in that city, and a total count of posters in that city, for every city in the country that posters have been made for.
def country_page(request, country_name):
country = get_object_or_404(Country, name__iexact=country_name)
posters = Poster.objects.filter(city__country=country)
variables = RequestContext(request, {
'location' : country,
'posters' : posters,
})
return render_to_response('country_page.html', variables)
Any help would be appreciated.
What you’re looking for is a ‘group by’ in sql land.
The below thread has some interesting insights, bottom line is you need raw sql to do a true group by, but I suspect for your needs you can just do a little post processing to do the grouping:
Now you can get the posters by city like this to use from the template:
background:
How to query as GROUP BY in django?