从Django中的嵌套if语句中断开for循环

时间:2015-06-02 19:13:45

标签: django

有没有办法在//I want to get the data from SampleId = 2, 4 and 6 added together //from the Foo object and put into the Data of the new Bar object. List.GroupBy(l => l.CompanyId).Select( x => new Bar { CompanyId = x.Key, ????? } ); 语句中突破这个for循环。目前我们的数据库错误地存储了多个主要电话,我想在找到第一个主要电话后突破for循环。提前感谢您的帮助。

if

更新

或者通过在{% for phone in user_phones %} {% if phone.primary %} <div>{% if phone.type %}{{ phone.type|title }}: {% endif %}<span itemprop="telephone">{{ phone.phone_format }}</span></div> {% endif %} {% endfor %} 分支

中创建变量来使if条件失败

2 个答案:

答案 0 :(得分:2)

如果您必须留在模板图层中,可以使用regroup

{% regroup user_phones|dictsort:"primary" by primary as phones_list %}

{% for phone in phones_list %}
    {% if phone.grouper %}
    {{ phone.list.0.type }}
    {% endif %}
{% endfor %}

它的作用

regroupdictsort过滤器(也适用于查询集)一起将user_phones中的实例按primary的值分组。

regroup会添加一个名为grouper的属性,当按boolprimary的值)进行分组时,该属性将为True或{{ 1}}。

False然后迭代for提供的变量phones_list。由于我们按regroup对结果进行了排序,因此primary会告诉我们何时使用{% if phone.grouper %}命中这些项目。

primary == True将属于某个组的项目打包到属性regroup中。因此,可以使用listphone.list.0.type等访问第一项。

<强> 注意:
如果您需要多次访问phone.list.0.phone_format,可以将其分配给变量(使用with):

foo.list.0

答案 1 :(得分:0)

Django模板中没有break。您可以在视图中处理它,方法是将您要查找的primary phone存储到变量中,然后在模板中调用它。

相关问题