python 如何合并Django查询集结果,从匹配键中收集值?

qlvxas9a  于 2023-02-15  发布在  Python
关注(0)|答案(1)|浏览(103)

我的网站Views.py

context['user'] = User.objects.filter(code='01').values('name', 'phone')
print(context['user'])

目前的结果如下:

<QuerySet [{'name': 'John', 'cellphone': '1234567890'}, {'name': 'Doe', 'cellphone': '1234512345'}]>

如何从模板中获得这样的结果?

{% 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
e5nqia27

e5nqia271#

循环两次。

<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 %}

相关问题