How to merge Django queryset result, collecting values from matching keys?
Question:
My Views.py
context['user'] = User.objects.filter(code='01').values('name', 'phone')
print(context['user'])
The current results are as follows:
<QuerySet [{'name': 'John', 'cellphone': '1234567890'}, {'name': 'Doe', 'cellphone': '1234512345'}]>
How can I get a result like this from templates?
{% for u in user %}
<span>name :</span> <span> {{ u.name }} / </span>
<span>cellphone :</span> <span> {{ u.cellphone }}</span>
{% endfor %}
# want result
name : John, Doe / cellphone : 1234567890, 1234512345
Answers:
Loop twice.
<span>name :</span>
{% for u in user %}
{% if not forloop.first %}, {% endif %}{{ u.name }}
{% endfor %}
<span> / cellphone :</span>
{% for u in user %}
{% if not forloop.first %}, {% endif %}{{ u.cellphone }}
{% endfor %}
My Views.py
context['user'] = User.objects.filter(code='01').values('name', 'phone')
print(context['user'])
The current results are as follows:
<QuerySet [{'name': 'John', 'cellphone': '1234567890'}, {'name': 'Doe', 'cellphone': '1234512345'}]>
How can I get a result like this from templates?
{% for u in user %}
<span>name :</span> <span> {{ u.name }} / </span>
<span>cellphone :</span> <span> {{ u.cellphone }}</span>
{% endfor %}
# want result
name : John, Doe / cellphone : 1234567890, 1234512345
Loop twice.
<span>name :</span>
{% for u in user %}
{% if not forloop.first %}, {% endif %}{{ u.name }}
{% endfor %}
<span> / cellphone :</span>
{% for u in user %}
{% if not forloop.first %}, {% endif %}{{ u.cellphone }}
{% endfor %}