Loading lesson path
Concept visual
A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.
Loop through the items of a list:
{% for x in fruits %}<h1></h1>
{% endfor %}Loop through a list of dictionaries:
{% for x in cars %}<h1></h1> <p></p> <p></p>
{% endfor %}Data in a model is like a table with rows and columns.
Member model we created earlier has five rows, and each row has three columns: id firstname lastname phone joined_date
5551234
Formula
2022 - 01 - 055557777
Formula
2022 - 04 - 015554321
Formula
2021 - 12 - 245551234
Formula
2021 - 05 - 015559876
Formula
2022 - 09 - 29
When we fetch data from the model, it comes as a QuerySet object, with a similar format as the cars example above: a list with dictionaries:<QuerySet [
{
'id': 1,
'firstname': 'Emil',
'lastname': 'Refsnes',
'phone': 5551234,
'joined_date': datetime.date(2022, 1, 5)
},
{
'id': 2,
'firstname': 'Tobias',
'lastname': 'Refsnes'
'phone': 5557777,
'joined_date': datetime.date(2021, 4, 1)
},
{
'id': 3,
'firstname': 'Linus',
'lastname': 'Refsnes'
'phone': 5554321,
'joined_date': datetime.date(2021, 12, 24)
},
{
'id': 4,
'firstname': 'Lene',
'lastname': 'Refsnes'
'phone': 5551234,
'joined_date': datetime.date(2021, 5, 1)
},
{
'id': 5,
'firstname': 'Stalikken',
'lastname': 'Refsnes'
'phone': 5559876,
'joined_date': datetime.date(2022, 9, 29)
}]>
Loop through items fetched from a database:
{% for x in members %}<h1></h1> <p>
</p>
{% endfor %}The reversed keyword is used when you want to do the loop in reversed order.
{% for x in members reversed %}<h1></h1> <p>
</p>
{% endfor %}The empty keyword can be used if you want to do something special if the object is empty.
<ul>
{% for x in emptytestobject %}<li></li>
{% empty %}Formula
< li > No members </li >{% endfor %}</ul> The empty keyword can also be used if the object does not exist:
<ul>
{% for x in myobject %}<li></li>
{% empty %}Formula
< li > No members </li >{% endfor %}</ul>
Django has some variables that are available for you inside a loop: forloop.counter forloop.counter0 forloop.first forloop.last forloop.parentloop forloop.revcounter forloop.revcounter0 forloop.counter The current iteration, starting at 1.
<ul>
{% for x in fruits %}<li></li>
{% endfor %}</ul> forloop.counter0 The current iteration, starting at 0.
<ul>
{% for x in fruits %}<li></li>
{% endfor %}</ul> forloop.first Allows you to test if the loop is on its first iteration.