sql-noob
sql-noob

Reputation: 413

How to get queryset value outside of loop in Django template?

I have this below scenario as an example

Current scenario

{% for city in cities %}
    <div id="{{city.country}}">
        <p>Choose a city</p>
        <li>{{ city.name }}</li>
    </div>
{% endfor %}

What I want

<div id="{{city.country}}">
    <p>Choose a city</p>    
       {% for city in cities %}
           <li>{{ city.name }}</li>
       {% endfor %}    
</div>

How can I achieve that? Thanks

Upvotes: 1

Views: 898

Answers (2)

frnhr
frnhr

Reputation: 12903

Maybe using the built in {% regroup %} template tag is more elegant.

It would be something along these lines (not tested):

{% regroup cities by country as country_list %}

{% for country in country_list %}
    <div id="{{country.grouper}}">
        <p>Choose a city</p>    
        {% for city in country.list %}
            <li>{{ city.name }}</li>
        {% endfor %}    
    </div>
{% endfor %}

Interestingly, the example in official Django docs also uses cities and countries. Check it out (linked above).

Upvotes: 2

sql-noob
sql-noob

Reputation: 413

Like @erework said I restructured the data in my view. If you have any better ways, feel free to edit. Below is how I did it:

#views.py
from django.conf import settings
cities = []
for country in settings.COUNTRIES:
    cities.append([country, City.objects.filter(country=country)])


#cities.html
{% for country, city in cities %}
    <div id="{{country}}">
        <p>Choose a city</p>
        <li>{{ city.name }}</li>
    </div>
{% endfor %}

I wanted my cities list to be sorted by country hence I put the data into a list. Also I only had less than 10 countries so I had a list of them in settings file.

Upvotes: 0

Related Questions