I have a Django model that looks like this:
class City(models.Model):
country = models.CharField(max_length=50)
city = models.CharField(max_length=50)
population = models.IntegerField()
What I want to do in my template is print a list of cities grouped by country, like so:
Canada Calgary Montreal Toronto Mexico Juarez United States Atlanta Chicago Denver
I can order by country name easily enough, but I want to print the model’s country name as a heading only the first time I see it in the for loop. Is there a sane way to do this in Django?
Is there something I can do in the view or query to give the template a boolean value for “first occurrence”, or a clever way to do this in the template?
See
regroup, you’d do something like this: