tags:

views:

455

answers:

2

I jumped into learning django recently.

I am rendering my template with citylist like,

{'citylist': Cities.objects.all()}

And want to reqroup on country in template (same as in django-docs) below:

{% regroup citylist by country as coutrylist %}

<ul>
{% for country in countrylist %}
    <li>{{ country.grouper }}
    <ul>
        {% for c in country.list %}
        <li>{{ c.name }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

but i get some unextpected results,

France
  Strasbourg

Australia
  Penrith
  Sydney

US
  Larsen Bay

France
  Reims

US
  Avenal

I dont think i am doing something wrong in my template. Or its a bug??

+5  A: 

Of course you are doing wrong with your template. Not in the code, but with data you injecting in.

To correct it, please change your context to

{'citylist': Cities.objects.all().order_by('country')}

If you read django-docs (as you mentioned) a bit more closely, you would have read something that says like your view should order the data according to how you want to display it.

And forget word bug until you level yourself to intermediate, as a respect to something you jumped in to learn.

simplyharsh
Your answer being right doesn't make it OK for your attitude to be wrong.
ironfroggy
Agree with ironfroggy
Guðmundur H
simplyharsh
Hey dont worry @taurean. It was my lazy call to see it as bug.
What if the sort column is being pulled in by a select_related() clause, rather than all()?
Noah
+1  A: 

I would also like to point to the documentation for another solution. http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

You can sort your dictionary in the template.

{% regroup citylist**|dictsort:"country"** by country as countrylist %}