django中的for循环迭代

django中的for循环迭代,django,django-templates,Django,Django Templates,我的编码是: 观点 型号: class Post(models.Model): subject = models.CharField(max_length = 250) body = models.TextField() thread = models.ForeignKey('self', null = True, editable = False ) Show.html: {% for post in post_list %} {{pos

我的编码是: 观点

型号:

class Post(models.Model):
        subject = models.CharField(max_length = 250)
        body = models.TextField()
        thread = models.ForeignKey('self', null = True, editable = False )
Show.html:

{% for post in post_list %}
   {{post.id}}{{post.subject}}
{% endfor %}
{% for post_like in post_likes %}
   {% if post_like.post_id == post.id and post_like.user_id == user.id %} 
         U like this post{{post}}
   {% else %}
         {{post}}
   {% endif %}      
{% endfor %} 

在show.html的else部分中,它一次又一次地显示值。但我只需要一次。当我进入else条件时,我如何打破for循环。请帮助我。

Django的标记不能为您提供任何打破循环的方法。您只需在自己的视图中筛选集合,并在您的条件失败后对其进行切片,然后将其提供给模板。

您可能会使用
ifchanged
标记:


但是,您可能应该考虑将此逻辑移动到视图。

< P>如果您可以构造if语句来检测何时不输出任何内容,那么可以简单地在Office子句中不加任何东西:

{% for post_like in post_likes %}
   {% if post_like.post_id == post.id and post_like.user_id == user.id %} 
         U like this post{{post}}
   {% else %}
         {% if forloop.first %}
             {{post}}
         {%else%}{%endif%}
   {% endif %}      
{% endfor %} 

上面的方法可能不能完全满足您的需要-您必须自己进行调整。您唯一不能做的就是设置一个标志,表明这是else子句的第一个条目。

您可以使用此文件中的django自定义模板标记。如果您对使用它有疑问,请转到了解自定义模板标记

然后使用
{%load loop\u break%}
在模板中加载模板标记。然后,您可以按如下所示中断for循环:

{% for post_like in post_likes %}
    {% if post_like.post_id == post.id and post_like.user_id == user.id %} 
        U like this post{{post}}
    {% else %}
        {{post}}
        {{ forloop|break }}
    {% endif %}
{% endfor %}

这里,for循环将在进入else部分时中断。

此代码段在Python 2.7.6和Django 1.8.15中运行良好。谢谢
{% for post_like in post_likes %}
    {% if post_like.post_id == post.id and post_like.user_id == user.id %} 
        U like this post{{post}}
    {% else %}
        {{post}}
        {{ forloop|break }}
    {% endif %}
{% endfor %}