【问题标题】:for loop iteration in djangodjango中的for循环迭代
【发布时间】:2012-05-10 23:11:45
【问题描述】:

我的编码是: 意见

def showThread(request, thread_id)
    post_list     = Post.objects.filter(id = thread_id)
    post_likes    = PostLikes.objects.all()
    return render_to_response('show.html',locals(),context_instance=RequestContext(request))

型号:

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

显示.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 django-templates


    【解决方案1】:

    Django 的for 标签并没有为您提供任何跳出循环的方法。您只需在自己的视图中过滤集合,并在条件失败后对其进行切片并将其提供给您的模板。

    【讨论】:

      【解决方案2】:

      您可以使用django snippets page 中的 django 自定义模板标签。如果您对使用有疑问,请前往this page了解自定义模板标签。

      然后使用{% load loop_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 部分时中断。

      【讨论】:

      • 这个 sn-p 在 Python 2.7.6 和 Django 1.8.15 上运行良好。谢谢。
      【解决方案3】:

      您可能会使用ifchanged 标签:
      https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifchanged

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

      【讨论】:

        【解决方案4】:

        如果您可以构建 if 语句以检测何时不输出任何内容,则可以简单地在 else 子句中放置任何内容:

        {% 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 子句的第一个条目。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-07-13
          • 2021-12-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-27
          相关资源
          最近更新 更多