Как показать содержимое с zip в представлении с помощью django?
У меня есть приложение django. И я пытаюсь показать значения контента из бэкенда в шаблоне. Есть метод: show_extracted_data_from_file
где я комбинирую три метода:
class FilterText:
def total_cost_fruit(self):
return [3588.20, 5018.75, 3488.16, 444]
def total_cost_fruit2(self):
return [3588.20, 5018.75, 3488.99]
def total_cost_fruit3(self):
return [3588.20, 5018.75, 44.99]
def show_extracted_data_from_file(self):
regexes = [
self.total_cost_fruit(),
self.total_cost_fruit2(),
self.total_cost_fruit3,
]
matches = [(regex) for regex in regexes]
return zip(matches)
и я имею вид:
def test(request):
content_pdf = ""
filter_text = FilterText()
content_pdf = filter_text.show_extracted_data_from_file()
context = {"content_pdf": content_pdf}
return render(request, "main/test.html", context)
и html:
<div class="wishlist">
<table>
<tr>
<th>Method 1</th>
<th>Method 2</th>
<th>Method 3</th>
</tr>
{% for value in content_pdf %}
<tr>
<td>{{value.0}}</td>
<td>{{value.1}}</td>
<td>{{value.2}}</td>
</tr>
{% endfor %}
</table>
</div>
Но сейчас это выглядит так:
Method 1 Method 2 Method 3
[3588.2, 5018.75, 3488.16, 444]
[3588.2, 5018.75, 3488.99]
[3588.2, 5018.75, 44.99]
Но я хочу, чтобы они, конечно, были друг под другом:
Method 1 Method 2 Method 3
3588.2 3588.2 3588.2
5018.75, 44.99 3488.99
5018.75,
5018.75
3488.16
444
Вы можете работать с itertools.zip_longest(…)
[Python-doc], чтобы поместить None
значения, когда один из методов заканчивается, так:
from itertools import zip_longest
class FilterText:
def total_cost_fruit(self):
return [3588.20, 5018.75, 3488.16, 444]
def total_cost_fruit2(self):
return [3588.20, 5018.75, 3488.99]
def total_cost_fruit3(self):
return [3588.20, 5018.75, 44.99]
def show_extracted_data_from_file(self):
regexes = [
self.total_cost_fruit(),
self.total_cost_fruit2(),
self.total_cost_fruit3(),
]
return zip_longest(*regexes)
Вы также можете сделать это более удобным способом:
<div class="wishlist"> <table> <tr> <th>Method 1</th> <th>Method 2</th> <th>Method 3</th> </tr> {% for value0, value1, value2 in content_pdf %} <tr> <td>{{ value0 }}</td> <td>{{ value1 }}</td> <td>{{ value2 }}</td> </tr> {% endfor %} </table> </div>