I have problem. I need to populate one table with two different sets of data, one is queryset and the other is list. Is there any way to populate table with two sets of data using one {% for %}
statement?
Something like {% for categories, expenses in categoriesList and expensesList %}
.
Asked
Active
Viewed 172 times
1

kapisolec
- 123
- 12
-
Exactly how would that go? Are `categoriesList` and `expenseList` guaranteed to have the same length? How would you *render* the data? – Willem Van Onsem Oct 06 '20 at 17:39
-
Is it possible to change the query set to a list too. Then maybe use the zip function to iterate over both. Link for reference: [Convert query set to list](https://stackoverflow.com/questions/4424435/how-to-convert-a-django-queryset-to-a-list) – twothreezarsix Oct 06 '20 at 17:45
-
They have the same length. I need to with each iteration render expenses from expensesList, its only one integer, but with categoriesList I have much more (id, description, category etc.). Ideal would be if I could include expensesList to the categoriesList, but I don't know how and if it's possible to add list to queryset. – kapisolec Oct 06 '20 at 17:57
1 Answers
4
You can work with a zip
. In yourr view, you can prepare this with:
def some_view(request):
categoriesList = …
expensesList = …
context = {
'categoriesList': categoriesList,
'expensesList': expensesList,
'categoriesExpenses': zip(categoriesList, expensesList)
}
return render(request, 'some_template.html', context)
in the template, you can then enumerate over the categoriesExpenses
:
{% for categories, expenses in categoriesExpenses %}
…
{% endfor %}
that being said, if the categoriesList
is a list of categories
for the expenses
, likely there are more elegant and efficient ways to do this. If there is a ForeignKey
from the Expense
model to the Category
you can load these and follow the relation.

Willem Van Onsem
- 443,496
- 30
- 428
- 555
-
1I should know about zip function at this point, thank you very much, I appreciate. – kapisolec Oct 06 '20 at 18:19